GATE / CS ARCHIVE

GATE CSE 2025 SET 1 / QUESTION 63

Tracing alternating decimal-digit extraction

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2025 Set 1 paper

GATE 2025 Set 1, Q63 2 marks · NAT
Report issue

Control Flow & Loop Tracing

Question 63, GATE 2025: Function gate(n) initializes newnum=turn=0,t=1; multiplies t by 10 while n≥t, then divides t by 10. While t>0 it sets d=n/t, n=n%t, t=t/10; if turn is 1 it appends d using newnum=10*newnum+d; then sets turn=(turn+1)%2. All divisions are integer divisions. What does gate(14362) print?
Tap to enlarge
Answer & solution

Official answer: 46

Approach: The first loop finds the highest decimal place value. The second consumes digits from left to right and retains alternating positions.
For n=14362, t grows through 1,10,100,1000,10000,100000. The condition then fails and t is divided by 10, giving 10000.
The digit iterations are: d=1, remainder 4362, turn=0, so skip; d=4, remainder 362, turn=1, so newnum=4; d=3, remainder 62, turn=0, so skip; d=6, remainder 2, turn=1, so newnum=10×4+6=46; d=2, remainder 0, turn=0, so skip. The place value becomes zero and the loop ends.
The program therefore prints 46, the digits in positions two and four from the left. The alternating flag is tested before it is toggled, so the first digit is skipped. For this concrete input all arithmetic fits in int; possible overflow for much larger arguments is irrelevant to this execution.

Original paper, page 63 · Answer key