Question:

Consider the following C code:

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

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

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

What is the output?

Show Hint

In loops, always carefully track the variable increments and the order of function calls. Be sure to account for changes in the loop counter inside the loop body.
Updated On: Mar 9, 2025
  • 40
  • 46
  • 50
  • 30
Hide Solution
collegedunia
Verified By Collegedunia

The Correct Option is B

Solution and Explanation

Step 1: Analyze the for loop.

- The loop starts with \( n = 1 \). In each iteration of the loop:
- \( n++ \) increments \( n \) to 2 before the function calls.
- Then, \( f(n) \) is called with \( n = 2 \).


Step 2: Function call analysis.


1. For \( n = 1 \), after the increment, \( n = 2 \):
\[ f(2) = g(4) = 10 + 4 = 14 \] So, \( sum = 14 \).

2. For \( n = 2 \), after the increment, \( n = 3 \):
\[ f(3) = g(6) = 10 + 6 = 16 \] So, \( sum = 14 + 16 = 30 \).

After the loop ends, \( sum = 46 \).

Thus, the correct answer is \( 46 \).
Was this answer helpful?
0
1