in Programming in C retagged by
488 views
6 votes
6 votes

What will be the output of following program ?

#include <stdio.h>
int thefunction(int a) {
    static int b = 0;
    b++;
    a = a + b;
    return a;
}
int main() {
    int b = 0;
    int i;
    for (i = 1; i <= 3; i++) {
        b = b + thefunction(i);
    }
    printf("%d\n", b);
    return 0;
}
in Programming in C retagged by
488 views

2 Answers

4 votes
4 votes

for i=1

    b=b + thefunction(1)

    thefunction returns returns 2

     so b becomes 2

now for i = 2

    b = 2 + thefunction(2)

    thefunction returns 4

    so b becomes 6

finally, for i = 3

   b = 6 + thefunction(3)

   thefunction returns 6

   the final value of b is updated to 12 and it is printed.

 

 

 

 

2 Comments

how theFunction returns 4  for i=2 ? Each time b will be 0 na ?
1
1

@pranavbhosle_ The keyword static does the job.


Static variables have the property of preserving their value even after they are out of their scope. Hence, a static variable preserves its previous value in its previous scope and is not initialized again in the new scope. 

 

Try running the code without the static keyword, then thefunction will return x+1, where x is the parameter passed.

 

2
2
0 votes
0 votes

For i = 1: b is updated to 0 + thefunction(1).

In the thefunction(1), a becomes 1 + 1 = 2 (since b starts at 0 and gets incremented to 1), and it returns 2.

So, b becomes 0 + 2 = 2.

 

For i = 2: b is updated to 2 + thefunction(2).

In the thefunction(2), a becomes 2 + 2 = 4 (since b is now 1 and gets incremented to 2), and it returns 4.

So, b becomes 2 + 4 = 6.

 

For i = 3: b is updated to 6 + thefunction(3).

In the thefunction(3), a becomes 3 + 3 = 6 (since b is now 2 and gets incremented to 3), and it returns 6.

So, b becomes 6 + 6 = 12.

 

Therefore, the output of the code will be: 12

Answer:

Related questions