IAE Academy

GATE 2025 CS2 Q.63: solution and answer

GATE 2025 · CS2Q.63 · 2 marks · NAT

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)

See the question in the paper

Answer and solution

ANSWER

The output of the program is 46.

Official answer: 46Source: Official answer key, GATE 2025 CS2 (IIT Roorkee)

  1. g(n) returns n+10, so f(n) = g(n*2) = 2n+10.

  2. The for-loop runs for n=1 and n=2 (loop stops when n<3 fails, i.e. at n=3).

  3. n=1: f(1) = 2(1)+10 = 12. g(f(1)) = g(12) = 12+10 = 22. sum = 0+22 = 22.

  4. n=2: f(2) = 2(2)+10 = 14. g(f(2)) = g(14) = 14+10 = 24. sum = 22+24 = 46.

  5. The loop ends; printf outputs the value of sum, which is 46.

KEY IDEA

Trace nested function calls exactly in evaluation order: g(f(n)) first fully evaluates f(n), which itself calls g(n*2), before the outer g is applied to that result.

WATCH OUT FOR

Applying g only once per loop iteration (forgetting that f(n) internally already calls g), e.g. computing sum += n*2+10 instead of sum += g(f(n)) = (n*2+10)+10, which gives 36 instead of 46.

From the GATE 2025 CS2 paper. Every question of this paper · Download the full paper · All 7 Functions & scope questions, with notes

More Functions & scope questions