Skip to content
Official PYQ · 2025

GATE CS 2025 Set 1 Q53 — Programming in C

Explain with AI

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 CC program is ________. (Answer in integer)

View worked solution

Answer: 46:46

Let's trace the execution of the function gate(14362) step-by-step:

Step 1: Determine the initial value of tt
The first while (n >= t) loop finds the smallest power of 1010 greater than nn. For n=14362n = 14362, the loop terminates when t=100000t = 100000.
After the loop, t /= 10; sets t=10000t = 10000.

Step 2: Extract digits and construct newnum
The second while (t > 0) loop extracts the digits of nn from left to right (most significant to least significant) and alternates selecting them using the turn flag:

  • Iteration 1:
    • d=14362/10000=1d = 14362 / 10000 = 1, n=14362%10000=4362n = 14362 \% 10000 = 4362, t=1000t = 1000.
    • Since turn == 0, newnum remains 00.
    • turn becomes (0+1)%2=1(0 + 1) \% 2 = 1.
  • Iteration 2:
    • d=4362/1000=4d = 4362 / 1000 = 4, n=4362%1000=362n = 4362 \% 1000 = 362, t=100t = 100.
    • Since turn == 1, newnum = 10 * 0 + 4 = 4.
    • turn becomes (1+1)%2=0(1 + 1) \% 2 = 0.
  • Iteration 3:
    • d=362/100=3d = 362 / 100 = 3, n=362%100=62n = 362 \% 100 = 62, t=10t = 10.
    • Since turn == 0, newnum remains 44.
    • turn becomes (0+1)%2=1(0 + 1) \% 2 = 1.
  • Iteration 4:
    • d=62/10=6d = 62 / 10 = 6, n=62%10=2n = 62 \% 10 = 2, t=1t = 1.
    • Since turn == 1, newnum = 10 * 4 + 6 = 46.
    • turn becomes (1+1)%2=0(1 + 1) \% 2 = 0.
  • Iteration 5:
    • d=2/1=2d = 2 / 1 = 2, n=2%1=0n = 2 \% 1 = 0, t=0t = 0.
    • Since turn == 0, newnum remains 4646.
    • turn becomes (0+1)%2=1(0 + 1) \% 2 = 1.

The loop terminates because t=0t = 0. The function returns newnum, which is 46.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions