retagged by
8,473 views
24 24 votes

Consider the following C program:

#include <stdio.h>

int g(int n) {
    return (n+10);
}

int f(int n) {
    return g(n*2);
}

int main() {
    int sum, n;
    sum=0;
    for (n=1; n<3; n++)
         sum += g(f(n));
    printf ("%d", sum);
    return 0;
}

The output of the given C program is ___________. (Answer in integer)

4 Answers

14 14 votes
Let us first expand the expression given in the main function;

sum+=g(f(n)) can be written as sum=sum+g(f(n))

now, coming to the for loops, it is run two times.

when $n=1,1<3:T$,it is called as $0+g(f(1))$.

when $f(1)$ is called it return $g(2)$ which is go to function g(n) where it is executed $10+2$ and return $12$ to main fuction.again

sum=0+g(12), now we call one more time $g(n)$ this time it return $10+12=22$.Therefore final value of the sum after the first iteration is $22.$

now increment $n++$ gives $n=2,2<3:T$, loop will run one more time as $sum=22+g(f(2))$

when $f(2)$ is called it return g(4) which go to function $g(4)$ and it return as $10+4=14$ to main fuciton.

so $sum=22+g(14)$, now $g(14)$ will return again $10+14=24$. so the final value of the sum is $22+24=46$

so the output of the given program is $46.$
5 5 votes

int g(int n) {
    return (n+10);
}


int f(int n) {
    return g(n*2);
}

for (n = 1; n < 3; n++) 
    sum += g(f(n));

When n = 1:

  • f(1)g(1*2)g(2)2 + 10 = 12   // in this step, someone make mistake

  • g(f(1))g(12)12 + 10 = 22

When n = 2:

  • f(2)g(2*2)g(4)4 + 10 = 14

  • g(f(2))g(14)14 + 10 = 24

 
sum = 22 + 24 = 46
ans is 46
3 3 votes

When n = 1:
         f(1) = g(1 * 2) = g(2) = 2 + 10 = 12


         g(f(1)) = g(12) = 12 + 10 = 22


         sum = sum + 22 => sum = 0 + 22 = 22

         When n = 2:
         f(2) = g(2 * 2) = g(4) = 4 + 10 = 14


         g(f(2)) = g(14) = 14 + 10 = 24


         sum = sum + 24 => sum = 22 + 24 = 46

Answer:
Position:
Show:

Related questions

31 31 votes
6 6 answers
12.7k
12.7k views
admin asked Feb 27, 2025
12,691 views
Consider the following C program:#include<stdio.h int main(){ int a; int arr[5] = {30,50,10}; int *ptr; ptr = &arr[0] + 1; a = *ptr; (*ptr)++; ptr++; printf("%d", a + (*p...
18 18 votes
6 6 answers
6.2k
6.2k views
Arjun asked Feb 27, 2025
6,211 views
int x=126,y=105; do { if(x>y) x=x-y; else y=y-x; } while(x!=y); printf("%d",x);The output of the given C code segment is _________. (Answer in integer)
33 33 votes
7 7 answers
14.0k
14.0k views
Arjun asked Feb 27, 2025
13,964 views
​​​​​Consider the following C program:#include <stdio.h void stringcopy (char *, char *); int main() { char a[30] = "@#Hello World!"; stringcopy(a, a+2); printf("%s\n",a)...
33 33 votes
2 2 answers
11.7k
11.7k views
Arjun asked Feb 27, 2025
11,747 views
Consider the following C program:#include <stdio.h int gate (int n) { int d, t, newnum, turn; newnum = turn = 0; t=1; while (n>=t) t *= 10; t /=10; while (t>0) { d = n/t;...