in Programming
630 views
7 votes
7 votes

The output for the following C program will be

#include <stdio.h>
int temp;
int new(int t)
{
	static int cal;
	cal = cal + t;
	return(cal);
}
int main()
{
	int t, p;
	for(t=0; t<=4; t++)
		p = new(t) + ++temp;
	printf("%d", p);
}
  1. 25
  2. 20
  3. 15
  4. Garbage Value
in Programming
by
630 views

2 Answers

4 votes
4 votes
Best answer
new(t) = ( cal + t )

t = 0,
cal = 0, temp = 0, 
p = new(0) + ++temp
p = (0 + 0) + 1 = 1
cal = 0, temp = 1,

t = 1,
cal = 0, temp = 1,
p = new(1) + ++temp
p = (0 + 1) + 2 = 3
cal = 1, temp = 2,

t = 2,
cal = 1, temp = 2,
p = new(2) + ++temp
p = (1 + 2) + 3 = 6
cal = 3, temp = 3,

t = 3,
cal = 3, temp = 3,
p = new(3) + ++temp
p = (3 + 3) + 4 = 10
​​​​​​​cal = 6, temp = 4,

t = 4,
cal = 6, temp = 4,
p = new(4) + ++temp
p = (6 + 4) + 5 = 15
​​​​​​​cal = 10, temp = 5,


​​​​​​​p = 15

selected by

4 Comments

is it applicable for all global variable ??
0
0
Yes .
1
1
got it. thnx a lot [email protected] anirudh
1
1
1 vote
1 vote

Static and global variables are both implicitly initialised to 0, if not explicitly initialised by the programmer.

temp is a global variable, so it is implicitly initialised to 0. Same for cal, which is a static variable.

Now if you follow the flow of control properly, answer is 15.

 

Option C

Answer:

Related questions