# GeeksforGeeks Questions

106 views
Need Explanation for this question:

int main()
{
static int i=5;
if(--i)
{
printf("F=%d\n",i);
main();
printf("Hai\n");
printf("%d\n",i);
}
}

Output:

F=4
F=3
F=2
F=1
Hai
0
Hai
0
Hai
0
Hai
0
1

If you dont know how static variables work:

https://www.geeksforgeeks.org/static-variables-in-c/https://www.geeksforgeeks.org/static-variables-in-c/

i is static so its lifetime is as long program is under execution and scope is the function/ block it is declared in.

Also I can see that in if() its --i and not -i

Initially i=5

Since --i = --5 =4 is not zero value of F=4 is printed. main is called

Since i is static, i's value is 4 and not 5.

i=4, Similarly i is decremented to 3 F=3 is printed and main() called

i=3, Then F=2 and main called

i=2,  F=1 and main called

i=1, Now, in if() i is first decremented to 0 now since its not equal to 0 block of if not executed and function returned.

Now i's value is 0 and after main is executed, the statements after it are executed and note that since value of i is not manipulated later all function has i=0.

And later following is printed:

Hai
0
Hai
0
Hai
0
Hai
0

0
Thanks for the reply. I am confused of why "hai" and "0" prints 4 times?

Moreover main(); function call is within if() block, as if() block was not satisfied for i=0 how comes the print of hai and 0 happens?

Kindly help me getting this out.

0

1) Initially main is called when i=5, i decremented to 4, for this hai will be printed after 2) executes

2) main is called, i=4, i decremented to 3, for this hai will be printed after 3) executes

3) main is called, i=3, i decremented to 2, for this hai will be printed after 4) executes

4) main is called, i=2, i decremented to 1, for this hai will be printed after 5) executes

5) main is called, i=1, i decremented to 0, and if not executed hence hai not printed.

--5 is executed so hai and 0 printed for 4)    once

--4 is executed so hai and 0 printed for 3)     twice

--3 is executed so hai and 0 printed for 2)   thrice

--2 is executed so hai and 0 printed for 1)   four times

--1 is executed so program terminated.

So total four times hai and 0 is printed

0
Thanks a lot for the detailed explanation.

## Related questions

1
226 views
Caption
1 vote
\begin{align*} & a[n] = \{x_1,x_2,x_3,x_4,....,x_n\} \text{ is an array of integers where } n,x_i > 0. \\ & A = \left [ \text{min}\left ( x_i,x_j \right ) \right ] \cdot \left ( j-i \right ) \text{ where } j > i \text{ and } i,j \leq n \\ & \text{What is the best time complexity to find out the value of } A_{\bf max} \; ? \end{align*}