IAE Academy

GATE 2025 CS1 Q.63: solution and answer

GATE 2025 · CS1Q.63 · 2 marks · NAT

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)

See the question in the paper

Answer and solution

ANSWER

The program prints 46.

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

  1. First while loop: t starts at 1 and is repeatedly multiplied by 10 while n (=14362) >= t, so t goes 1 -> 10 -> 100 -> 1000 -> 10000 -> 100000, stopping when t=100000 first exceeds n.

  2. The statement t /= 10 brings t back to 10000, the place-value of n's leading (most significant) digit.

  3. The second while loop (t>0) runs 5 times, each time extracting the top remaining digit via d=n/t and n=n%t, then shrinking t by /=10; turn starts at 0 (false) and toggles 0<->1 after every iteration.

  4. Iteration 1 (t=10000): d=1, n becomes 4362, t becomes 1000. turn was 0, so newnum stays 0. turn becomes 1.

  5. Iteration 2 (t=1000): d=4, n becomes 362, t becomes 100. turn was 1, so newnum = 10*0+4 = 4. turn becomes 0.

  6. Iteration 3 (t=100): d=3, n becomes 62, t becomes 10. turn was 0, so newnum stays 4. turn becomes 1.

  7. Iteration 4 (t=10): d=6, n becomes 2, t becomes 1. turn was 1, so newnum = 10*4+6 = 46. turn becomes 0.

  8. Iteration 5 (t=1): d=2, n becomes 0, t becomes 0. turn was 0, so newnum stays 46. turn becomes 1.

  9. Loop exits since t=0; the function returns newnum=46, which main() prints.

KEY IDEA

The function alternately drops and keeps digits of n, most-significant first: turn starts false (0) so the leading digit is dropped, then toggles true/false each iteration. For 14362 (digits 1,4,3,6,2 from MSD), digit 1 is dropped, 4 is kept, 3 is dropped, 6 is kept, 2 is dropped, leaving newnum built from 4 then 6 giving 46.

WATCH OUT FOR

Forgetting that turn starts at 0 (false) and toggles AFTER each digit is examined, so the loop skips appending the very first (most significant) digit — leading to including digit 1 and wrongly getting 146 instead of 46. Another slip is misjudging where the first while loop stops: it multiplies t until t first EXCEEDS n (t=100000), and only the following t/=10 brings it to the leading digit's place value (10000), not to 1000.

From the GATE 2025 CS1 paper. Every question of this paper · Download the full paper · All 7 C basics questions, with notes

More C basics questions