1,042 views
9 votes
9 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

2 Answers

Best answer
3 votes
3 votes
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
1 votes
1 votes

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

3 votes
3 votes
2 answers
2
8 votes
8 votes
2 answers
3
1 votes
1 votes
3 answers
4