GATE 2013 COMPUTER SCIENCE & INFORMATION TECH. – CS – C Programming | Q. 42
Note that the first parameter is passed by reference, whereas the second parameter is passed by value.
int f(int &x, int c) { c = c - 1; if (c == 0) return 1; x = x + 1; return f(x, c) * x; }
Solution
int f(int &x, int c) { c = c - 1; if (c == 0) return 1; x = x + 1; return f(x, c) * x; }
int p = 5; f(p, p);
c → 5 (copy)
c = 5 - 1 c = 4
x = x + 1 x = 6
p = 6
return f(x, 4) * x;
p = 6
c = 3; x = x + 1;
p = 7
f(x, 3) * x
c = 2; x = x + 1;
p = 8
f(x, 2) * x
c = 1; x = x + 1;
p = 9
f(x, 1) * x
c = 0;
return 1;
p = 9
1 × 9 = 9
9 × 9 = 81
81 × 9 = 729
729 × 9 = 6561
Note on Call by Value & Call by reference
Call by Value and Call by Reference
A simple way to understand these two concepts is to imagine a classroom and a student’s marks record.
🟢 Call by Value – Give a Copy
Imagine a teacher gives a student a photocopy of the marks record. The student changes the photocopy from 80 to 100.
The teacher’s original record is still 80.
Simple rule:
“I give you a copy. You can change your copy,
but my original does not change.”
🔵 Call by Reference – Access the Original
Now imagine that the teacher gives the student access to the original marks record. If the student changes the marks from 80 to 100, the original record also becomes 100.
Simple rule:
“I give you access to the original.
If you change it, my original changes too.”
Quick Comparison
| Call by Value | Call by Reference |
|---|---|
| A copy is passed. | Access to the original is provided. |
| Changing the copy does not change the original. | Changing the original changes the caller’s value. |
🟢 Call by Value → Copy
🔵 Call by Reference → Original

