in Programming in C edited by
14,932 views
29 votes
29 votes

The value of $j$ at the end of the execution of the following C program:

int incr (int i)
{ 
    static int count = 0;
    count = count + i;
    return (count);
} 
main () { 
    int i, j; 
    for (i = 0; i <= 4; i++)
       j = incr (i);
} 

is:

  1. $10$
  2. $4$
  3. $6$
  4. $7$
in Programming in C edited by
14.9k views

2 Answers

36 votes
36 votes
Best answer

Answer: (A)

  • At $i=0, j=0$
  • At $i=1, j=1$
  • At $i=2, j=3$
  • At $i=3, j=6$
  • At $i=4, j=10$
edited by

4 Comments

A static local variable is a place to hide data form other functions but retain it for future calls of the same function.
2
2
edited by

In main function inside the for loop incr(i) function call is done for each value of i from 0 to 4 and in the incr(function definition) just adding all of them (because of count variable is static and it retains previously result).

So, if i goes from 0 to 4(inside the main) then incr(function definition) last value returned will be –

0+1+2+3+4 = $\frac{4*5}{2}$ = 10

Similarly, for i goes from 0 to n incr last value returned will be –

0+1+2+….n = $\frac{n*(n+1)}{2}$

0
0
ans will be 10 0+1+2+3+4
0
0
0 votes
0 votes
They crux of the problem is, static int count = 0; will get executed only once.

Now, for

i=0, j =0

i=1, j=1

i=2, j=3

i=3, j=6,

i=4, j=10.

 

j=10, is the required answer to the given problem
Answer:

Related questions