313 views
2 votes
2 votes

Find the output of the following program
 

int m = 100, n= 200;
int fun1(int count);
int fun2(int p);

void main( )
{
int count;
for(count = 1; count <= 5; ++count)
printf(“%d”, fun1(count));
}
int fun1(int a)
{
int r, s;
r = fun2(a);
s = (r, 100)? (m + r): n;
return s;
}
int fun2(int a)
{
static int val = 1;
val * = a;
return(val);
}

1 Answer

Best answer
4 votes
4 votes

$\color{navy}{val}$ is static variable, i.e., it retains its value between function calls.

//fun2(): it returns the value stored in  val multiplied with passed value a
int fun2(int a) { 
static int val = 1;
val *= a;
return(val);
}
s = (r,100) ? (m + r): n; // precedence of comma is from left to right
s = 100 ? (m + r): n;
s = m + r;
int fun1(int a) {
int r, s;
r = fun2(a);
s = m + r; 
return s;
}

$\tt fun1()$ calls $\tt fun2()$ first and uses it's returned value as $r$ in ternary operator.

Count $= 1$ : $val = 1$(initially), $val = 1*a$ ($a = 1$), $val = 1$ 
Now. $fun1()$ computes $\color{olive}{s = m + r = 100 + 1 = 101}$
So for $\color{maroon}{count = 1}$, $\color{blue}{101}$ gets printed.

Count $= 2$ : $val = 1$(initially), $val = 1*a$ ($a = 2$), $val = 2$ 
Now. $fun1()$ computes $\color{olive}{s = m + r = 100 + 2 = 102}$
So for $\color{maroon}{count = 2}$, $\color{blue}{102}$ gets printed.

Count $= 3$ : $val = 2$(initially), $val = 2*a$ ($a = 3$), $val = 6$ 
Now. $fun1()$ computes $\color{olive}{s = m + r = 100 + 6 = 106}$
So for $\color{maroon}{count = 3}$, $\color{blue}{106}$ gets printed.

Count $= 4$ : $val = 6$(initially), $val = 6*a$ ($a = 4$), $val = 24$ 
Now. $fun1()$ computes $\color{olive}{s = m + r = 100 + 24 = 124}$
So for $\color{maroon}{count = 4}$, $\color{blue}{124}$ gets printed.

Count $= 5$ : $val = 24$(initially), $val = 24*a$ ($a = 5$), $val = 120$ 
Now. $fun1()$ computes $\color{olive}{s = m + r = 100 + 120 = 220}$
So for $\color{maroon}{count = 5}$, $\color{blue}{220}$ gets printed.

The above program is similar to $\Rightarrow$

int  main( ) {
int count,ans,val = 1;
for(count = 1; count <= 5; ++count) {
    ans = val*count  + 100;
    val *= count;
    printf("%d\n", ans);
}
return 0;
}
selected by

Related questions

3 votes
3 votes
3 answers
1
Laxman Ghanchi asked May 19, 2023
1,113 views
#include<stdio.h void print(int n) { printf("Hello "); if(n++ == 0) return ; print(n); n++; } int main() { void print(); print(-4); }How many times printf execute?? And H...
0 votes
0 votes
1 answer
2
Laxman Ghanchi asked May 19, 2023
657 views
#include<stdio.h>void print(int n){ printf("Hello "); if(n++ == 0) return ; print(n); n++;}int main(){ void print(); print(-4);}
1 votes
1 votes
0 answers
4