The Gateway to Computer Science Excellence
0 votes
68 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
in Algorithm Challenges by (25 points) | 68 views
+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.

 

Thanks in Advance!
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.

Please log in or register to answer this question.

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,645 questions
56,615 answers
195,895 comments
102,341 users