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)
Answer
46
Explanation
Compose the two functions: \(f(n) = g(2n) = 2n + 10\), so \(g(f(n)) = 2n + 20\).
The loop runs only for \(n = 1\) and \(n = 2\), because the condition is \(n < 3\):
- \(n = 1\): \(f(1) = 12\) and \(g(12) = 22\).
- \(n = 2\): \(f(2) = 14\) and \(g(14) = 24\).
So sum ends at \(22 + 24 = 46\). Running the loop for \(n = 3\) as well would wrongly add 26.
Answer: 46