Functions

GATE CS previous year questions · 3 questions

GATE CS 2025 Set 1 | Question 63

NAT · 2 marks

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;
        n = n%t;
        t /= 10;
        if (turn) newnum = 10*newnum + d;
        turn = (turn + 1) % 2;
    }
    return newnum;
}
int main () {
    printf ("%d", gate(14362));
    return 0;
}

The value printed by the given C program is _______ . (Answer in integer)

Explanation

Answer: 46

The first loop multiplies t by 10 until it exceeds n, ending at \(t = 100000\); then t /= 10 gives \(t = 10000\), the place value of the leading digit. The second loop reads the digits of 14362 from left to right: 1, 4, 3, 6, 2.

turn starts at 0 and flips after every digit, so only the 2nd and 4th digits are appended: newnum becomes 4 and then \(10 \times 4 + 6 = 46\). The digits 1, 3 and 2 are skipped.

Answer: 46

GATE CS 2025 Set 2 | Question 63

NAT · 2 marks

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)

Explanation

Answer: 46

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

GATE CS 2024 Set 2 | Question 13

MCQ · 1 mark · −0.33

Consider the following C program. Assume parameters to a function are evaluated from right to left.

#include <stdio.h>

int g(int p) { printf("%d", p); return p; }
int h(int q) { printf("%d", q); return q; }

void f(int x, int y) {
  g(x);
  h(y);
}

int main() {
  f(g(10),h(20));
}

Which one of the following options is the CORRECT output of the above C program?

Options for GATE CS 2024 Set 2 | Question 13

Explanation

Answer: (A)

Follow the calls in order.

  • In main, the arguments of f are evaluated right to left: h(20) runs first and prints 20, then g(10) prints 10.
  • f(10, 20) then runs its body in order: g(x) prints 10 and h(y) prints 20.

Nothing separates the numbers, so the output is 20101020. Left-to-right evaluation would print 10, 20, 10, 20 instead, which is option D. Standard C leaves the order of argument evaluation unspecified, which is why the question fixes it.

Answer: A