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:
- The first
while (n >= t) t *= 10;loop stops att = 100000, andt /= 10;setst = 10000. - The second
while (t > 0)loop extracts the digits of14362from most significant to least significant (d = 1, 4, 3, 6, 2) whileturnstarts at0and toggles0, 1, 0, 1, 0:d = 1(turn = 0): ignored;turnbecomes1.d = 4(turn = 1):newnum = 4;turnbecomes0.d = 3(turn = 0): ignored;turnbecomes1.d = 6(turn = 1):newnum = 10*4 + 6 = 46;turnbecomes0.d = 2(turn = 0): ignored;turnbecomes1.
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.