Question

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)

Official answer and solution
Official answer
46
From
Official GATE 2025 answer key

Solution

Trace how t extracts the decimal digits of 14362 from left to right while turn alternates between 0 and 1.

For n = 14362:

  1. The first while (n >= t) t *= 10; loop stops at t = 100000, and t /= 10; sets t = 10000.
  2. The second while (t > 0) loop extracts the digits of 14362 from most significant to least significant (d = 1, 4, 3, 6, 2) while turn starts at 0 and toggles 0, 1, 0, 1, 0:
    • d = 1 (turn = 0): ignored; turn becomes 1.
    • d = 4 (turn = 1): newnum = 4; turn becomes 0.
    • d = 3 (turn = 0): ignored; turn becomes 1.
    • d = 6 (turn = 1): newnum = 10*4 + 6 = 46; turn becomes 0.
    • d = 2 (turn = 0): ignored; turn becomes 1.
  3. gate(14362) returns 46.
Final answer

46

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2025 Computer Science and Information Technology - Session 1 (CS1)
Question
63 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.