3,041 views

1 Answer

Best answer
5 5 votes

Output will be 5.

If the assingment $i=1$ was not there then output would be 7.

Notice that the statement static int i; initializes $i$ to $0$.

Here i is initialized to $0$. In first rec call value of $i$ is $0$ (before the assignment $i=1;$)

In second rec call, initially value of i is 2, but after assignment it becomes 1 again. It's nothing unusual. Just normal assignment.

In 3rd call, initially value of i is 2 (since last modified value of $i$ was $2$), but after assignment it becomes 1 again.

So static variable is retaining its value across function calls. It's just that we're reassigning it to 1 in the assignment $i = 1.$

• selected by
Position:
Show:

Related questions

6 6 votes
3 3 answers
275
275 views
GO Classes asked Jun 16
275 views
What is the output of the following code?#include <stdio.h int fun(int n) { static int step = 1; if (n <= 1) return n; step++; return n + fun(n - step); } int main() { pr...
7 7 votes
3 3 answers
322
322 views
GO Classes asked Jun 15
322 views
What is the output of the following code?#include <stdio.h int fun(int n) { static int x = 0; int y; if (n == 0) return 0; x++; y = fun(n - 1); return y + x; } int main()...
6 6 votes
2 2 answers
273
273 views
GO Classes asked Jun 13
273 views
What is the output of the following code?#include <stdio.h int fun(int n) { static int count = 0; if (n == 0) return count; count = count + n; return fun(n - 1); } int ma...
5 5 votes
3 3 answers
241
241 views
GO Classes asked Jun 11
241 views
What is the output of the following code?#include <stdio.h int add(int n) { static int total = 1; total = total + n; return total; } int main() { int i, ans = 0; for (i =...