[Solved] Can someone explain why is the total = 7 in the following code? with static int sum? [closed]


    #include <stdio.h>
    int i, j; 
    int madness(int x);
    int main(void) 
    {
    int i, total = 0;
    j = 1;
    for (i = 0; i<3; i++) { total += madness(i); }
    printf("Total = %d\n", total);
    return 0;
    }  

    int madness(int x) 
    {
     static int i;
     static int sum = 0;
     for (i = 0; i<x; i++, j++) { sum += j; }
     return sum;
     }

1st call to madness function with i=0;

since static variables initialize only once ,so with first call to madness function it assigns i=0 and sum=0.since x=0 in this function so value of sum remains the same and it returns 0.

2nd call to madness function with i=1;

Here we have x=1,j=1,sum=0 and function run loop

 for (i = 0; i<1; i++, j++) { sum += j; }

so we get sum=1 and the value of j got 2 Now which will be used in the next function call.Now j becomes 2 and function return 1. so it’s added to our total .Now total becomes 1.

3rd call to madness function with i=2;

here x=2,j=2,sum=1(from previous call static values remains the same)
Now you are smart enough to calculate this result

for (i = 0; i<2; i++, j++) { sum += j; }

here sum becomes 6 and return this value . since our previous value of total is 1 .Now it becomes 6+1=7 Which is your required answer.

2

solved Can someone explain why is the total = 7 in the following code? with static int sum? [closed]