GATE 2025 CS (CS1) – Question 63
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)
Practise this question in The GATE Grind →
Show answer and explanation
Correct answer: 46
Explanation
Trace `gate(14362)`:
- The first loop makes `t` the highest power of 10 not exceeding `n`: $t=10000$.
- In the second loop, `d = n/t` is the next digit from the left, and `turn` alternates 0, 1, 0, 1, 0. A digit is appended to `newnum` only when `turn` is 1.
| digit | turn before | action | newnum |
|---|---|---|---|
| 1 | 0 | skip | 0 |
| 4 | 1 | append | 4 |
| 3 | 0 | skip | 4 |
| 6 | 1 | append | 46 |
| 2 | 0 | skip | 46 |
The function returns the digits in even positions (2nd and 4th): **46**.