GATE / CS ARCHIVE

GATE CSE 2024 SET 1 / QUESTION 18

Trace an integer-division loop invariant

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

GATE 2024 Set 1, Q18 1 mark · MCQ
Report issue

Control Flow & Loop Tracing

Question 18, GATE 2024: A C program initializes int a=6, b=0, then executes while(a<10) { a=a/12+1; a+=b; }, followed by printf("%d",a). What happens in the intended execution model? A prints 9; B prints 10; C infinite loop; D prints 6.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Approach: Trace the first iteration, then determine whether the loop reaches a repeating state. Both operands of a/12 are integers.
1. The initial test 6<10 is true. Integer division gives 6/12=0, so a=a/12+1 sets a to 1.
2. The following a+=b adds zero, because b was initialized to 0 and is never changed. The first iteration ends with a=1, b=0.
3. If an iteration starts with a=1, then 1/12=0, and the same two assignments leave a=1 again. This state is therefore preserved indefinitely.
4. The condition a<10 remains true, so control never reaches the printf after the loop.
Answer: C. The expression contains “+1”, but it does not mean a is incremented each time: a is first replaced by the quotient a/12. This is the textbook execution interpretation of the supplied program.
The printed program uses typographic double quotation marks. Taken literally these are not valid C delimiters, so the program does not compile as printed. The answer above follows the intended textbook interpretation with ASCII quote delimiters.

Original paper, page 12 · Answer key