retagged by
707 views
7 votes
7 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;
}
retagged by

3 Answers

5 votes
5 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.

 

 

 

 

1 votes
1 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

483
views
1 answers
2 votes
GO Classes asked Jan 21
483 views
Consider the following two declarations for $\textsf{arr1}$ and $\textsf{arr2}:$int arr1[2][3]; int r1[3]; int r2[3]; int * arr2[2] = {r1, ... $(\operatorname{arr}2)=32$ bytes
511
views
1 answers
6 votes
GO Classes asked Jan 21
511 views
What will be the output of the following program?main() { int a[2][2] = { {1,2},{3,4} }; int(*p)[2][2]; p = &a; printf("%d", (*p)[0][0]); }$1$3$4$None of these
532
views
1 answers
6 votes
GO Classes asked Jan 21
532 views
What will be the output of the following C program?#include<stdio.h> void main() { int i=6; for(--i; --i; i--) { printf("%d",i); } }$42$31$Infinite loopNone of these