GATE / CS ARCHIVE

SUBJECT COLLECTION

Programming in C · Control Flow & Loop Tracing

29 questions, newest first

GATE CSE has asked 29 questions on Control Flow & Loop Tracing (Programming in C) from 1991 to 2025, in 23 of the 46 papers; the most recent is in GATE CSE 2025 Set 2. In the last five years it carried 0.8 marks per 100-mark paper on average, against 1.1 since 2003. Since 2014 the questions have been 7 NAT, 6 MCQ and 1 MSQ. 6 groups of questions here are solved the same way; “One per method” keeps the newest of each.

Browse topics
2 marks · NAT
Report issue

Tracing alternating decimal-digit extraction

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

1 mark · NAT
Report issue

Control Flow & Loop Tracing

Question 33, GATE 2025: Find the integer printed by this C fragment:
int x=126,y=105;
do { if(x>y) x=x-y; else y=y-x; } while(x!=y);
printf("%d",x);
Tap to enlarge
Answer & solution

Official answer: 21

Step through it (21 steps)

Trace the pair (x,y) after each execution of the body:
(126,105) → (21,105) → (21,84) → (21,63) → (21,42) → (21,21).
At the first step x>y, so only x changes. Thereafter y>x until equality is reached, so y is reduced repeatedly by 21. The loop test sees x==y after the fifth iteration and stops. The printed x is 21.

This is the subtraction version of Euclid's algorithm. Replacing a larger positive integer by its difference with the smaller preserves the set of common divisors, and hence the gcd. At termination the two equal positive values must equal gcd(126,105)=21. Remember that a do-while executes the body before testing its condition; here the initial values differ, so that distinction does not alter the trace. Answer: 21.

Original paper, page 26 · Answer key

1 mark · MCQ
Report issue

Trace an integer-division loop invariant

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

2 marks · MSQ
Report issue

Solve the repeated doubling-plus-constant loop

Control Flow & Loop Tracing

Question 48, GATE 2024: The C function f(int x,int y) runs for(int i=0;i<y;i++){x=x+x+y;} and returns x. Which statements hold in the intended integer model? A f(20,10)>2²⁰; B f(20,20)>2²⁰; C f(20,10)<2¹⁰; D f(10,20)>2²⁰. The exponents are 20 and 10, not the decimal numbers 220 and 210.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: B, D

Approach: Derive a closed form for the loop instead of expanding twenty iterations individually.
1. Let x_k be the value after k iterations, with initial value x_0. Since y is unchanged, x_(k+1)=2x_k+y. Adding y gives x_(k+1)+y=2(x_k+y).
2. Therefore x_k+y=2^k(x_0+y), or x_k=2^k(x_0+y)−y. For the positive inputs listed, the loop performs exactly y iterations.
3. f(20,10)=30×2¹⁰−10=30,710. This exceeds 2¹⁰=1,024 but is below 2²⁰=1,048,576, so both A and C are false.
4. f(20,20)=40×2²⁰−20=41,943,020, and f(10,20)=30×2²⁰−20=31,457,260. Both exceed 2²⁰, making B and D true.
Answer: B and D. This trace assumes an int wide enough for these values, such as a 32-bit signed int. On a narrow implementation signed overflow would invalidate the mathematical trace; the original does not specify int width.

Original paper, page 30 · Answer key

2 marks · NAT
Report issue

Control Flow & Loop Tracing

Question 48, GATE 2021: ANSI C function: int SimpleFunction(int Y[],int n,int x){int total=Y[0],loopIndex; for(loopIndex=1;loopIndex<=n-1;loopIndex++) total=x*total+Y[loopIndex]; return total;} Array Z has ten elements, all equal to 1. Find SimpleFunction(Z,10,2).
Tap to enlarge
Answer & solution

Official answer: 1023

The loop performs Horner evaluation. Starting at total=1, each of the nine iterations replaces total by 2*total+1. After k iterations total=2^(k+1)-1, so after nine iterations the result is 2^10-1=1023. All intermediate results are within even the minimum standard signed-int range.

The values after initialization and each iteration are 1,3,7,15,31,63,127,255,511,1023. An induction proves total after k loop iterations is 2k+1−1: base k=0 is 1, and 2(2k+1−1)+1=2k+2−1. More generally the function evaluates Y[0]xn−1+Y[1]xn−2+...+Y[n−1] in n−1 multiplications, which is Horner's method.

Original paper, page 39 · Answer key

2 marks · NAT
Report issue

Control Flow & Loop Tracing

Question 48, GATE 2020: Find pp(3,4) for these C functions:
int tob(int b,int *arr) {
 int i;
 for(i=0;b>0;i++) {
  if(b%2) arr[i]=1; else arr[i]=0;
  b=b/2;
 }
 return i;
}
int pp(int a,int b) {
 int arr[20]; int i,tot=1,ex,len;
 ex=a; len=tob(b,arr);
 for(i=0;i<len;i++) {
  if(arr[i]==1) tot=tot*ex;
  ex=ex*ex;
 }
 return tot;
}
Question 48, GATE 2020: Find pp(3,4) for these C functions:
int tob(int b,int *arr) {
 int i;
 for(i=0;b>0;i++) {
  if(b%2) arr[i]=1; else arr[i]=0;
  b=b/2;
 }
 return i;
}
int pp(int a,int b) {
 int arr[20]; int i,tot=1,ex,len;
 ex=a; len=tob(b,arr);
 for(i=0;i<len;i++) {
  if(arr[i]==1) tot=tot*ex;
  ex=ex*ex;
 }
 return tot;
}
Tap to enlarge
Answer & solution

Official answer: 81

Worked explanation

The first loop extracts bits from least significant to most significant. Its trace (b before division, stored bit) is (4,0),(2,0),(1,1), then b=0 and len=3. The second loop trace (i,bit,ex before squaring,tot after possible multiply) is (0,0,3,1),(1,0,9,1),(2,1,81,81). Squaring ex is outside the if, so it happens on all iterations; that placement is central. The final ex=6561 is not the returned variable. More generally the loop multiplies powers a2^i for the set bits of b, implementing exponentiation by repeated squaring, so pp(3,4)=34=81.

Derivation and answer

tob(4, arr) stores the low-to-high binary digits 0, 0, 1 and returns len=3. In pp, ex is successively 3, 9, 81. Only the third digit is 1, so tot changes from 1 to 81 then. The final squaring makes ex=6561 but does not change tot. Thus pp(3, 4) returns 81. All values here fit even a 16-bit signed int, so overflow does not alter this evaluation.

Original paper, page 15 · Answer key

2 marks · NAT
Report issue

Tracing a strict floating-point loop test

Control Flow & Loop Tracing

Question 52, GATE 2019: The C program initializes float sum=0.0,j=1.0,i=2.0 and repeats while(i/j>0.0625) { j=j+j; sum=sum+i/j; printf("%f\n",sum); }. How many times is sum printed?
Tap to enlarge
Answer & solution

Official answer: 5

Step through it (26 steps)

1. The loop test is evaluated before doubling j. Variable i remains 2 throughout, while j doubles once per successful iteration. The threshold is 0.0625=1/16.
2. At successive tests, j is 1,2,4,8,16,32, giving i/j equal to 2,1,1/2,1/4,1/8,1/16. The first five values are strictly larger than 1/16; the sixth is equal and fails the > comparison.
3. Each of those five successful tests enters the body exactly once, executes one printf, and changes j to the next power of two. Therefore there are 5 prints.
4. As a check on operation order, the terms added inside the body use the already doubled j: 1,1/2,1/4,1/8,1/16. The printed sums are 1,1.5,1.75,1.875,1.9375, normally shown with six digits after the decimal by %f.
5. The test that stops execution produces no print. These powers of two and binary fractions are exactly representable in ordinary binary floating point, so rounding does not alter this stopping point.

Original paper, page 15 · Answer key

2 marks · MCQ
Report issue

Two integer-halving loops

Control Flow & Loop Tracing

Question 32, GATE 2018: A 64-bit unsigned-long function initializes j=sum=0. It runs for(i=n;i>1;i=i/2) j++; then for(;j>1;j=j/2) sum++; returns sum. For n=2^40, choose A 4; B 5; C 6; D 40.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Method

The first loop sees i=2^40,2^39,…,2 before stopping at i=1, so its body runs 40 times. The second loop then uses integer division: 40→20→10→5→2→1. It executes for the first five of these values, not for the final 1. The two loops are consecutive, not nested: multiplying their iteration counts would not describe the return value. The exponent in 2^40 is essential and can be lost in text extraction.

Solution

The first loop halves i until 1, performing 40 iterations, hence j=40. The second loop has j values 40, 20, 10, 5, 2 before stopping at 1, so sum=5, B.

Original paper, page 13 · Answer key

2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 37, GATE 2017: Unsigned integers x,y,q,r are used for division by repeated subtraction: while(r>=y){r=r-y; q=q+1;}. Which initial condition guarantees termination and final x==y*q+r? A:(q==r)&&(r==0). B:(x>0)&&(r==x)&&(y>0). C:(q==0)&&(r==x)&&(y>0). D:(q==0)&&(y>0).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

1. To preserve the intended division relation, use the invariant x=yq+r. Option C initializes q=0 and r=x, so the invariant holds before the loop. It also ensures y>0.

2. One iteration replaces r by r-y and q by q+1. Therefore y(q+1)+(r-y)=yq+r=x: the invariant is preserved. The guard r≥y prevents unsigned subtraction underflow.

3. Since y is positive, r decreases on every iteration and cannot decrease forever. At exit 0≤r<y, so q and r are the quotient and remainder. B leaves q unconstrained, D leaves r unconstrained, and A neither establishes the invariant for arbitrary x nor excludes y=0. C is the sufficient condition.

Original paper, page 14 · Answer key

2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 34, GATE 2016: Fill the loop condition so this C function returns the maximum array element for all n≥1:
int max(int *p,int n){int a=0,b=n−1;while(____){if(p[a]<=p[b])a=a+1;else b=b−1;}return p[a];}
A: a!=n. B: b!=0. C: b>(a+1). D: b!=a.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

At each iteration discard an endpoint no greater than the other: if p[a]≤p[b], advance a; otherwise decrement b. A maximum remains in the surviving interval. Continue until a=b, then return that sole survivor. Condition b!=a is D; stopping with two candidates is premature.

The invariant is that at least one maximum of the original array lies between indices a and b inclusive. Discarding the smaller endpoint preserves this invariant, including ties because the other equal value remains. Each step reduces b−a by 1, so termination occurs after n−1 iterations at a=b. For n=1 the correct loop runs zero times. Option C would stop with two values, potentially returning the smaller left one; A and B tie termination to fixed endpoints rather than convergence.

Original paper, page 14 · Answer key

2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 65, GATE 2015: For positive integers x,y: q:=0; r:=x; while r≥y do {r:=r−y; q:=q+1}. Which postcondition holds? A r=qx+y and r<y; B x=qy+r and r<y; C y=qx+r and 0<r<y; D q+1<r−y and y>0.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Prove the invariant x=qy+r by initialization and preservation: (q+1)y+(r−y)=qy+r. The guard ensures subtracting y never makes r negative. Since positive y decreases r at every step, the loop terminates and the false guard gives r<y. Therefore q is the integer quotient and r the remainder with 0≤r<y. A remainder may be zero, so a strict lower bound such as that in C would be wrong.

Solution: Initially q=0, r=x, so x=qy+r. Each iteration replaces r by r−y and q by q+1, preserving that invariant. Positive y decreases nonnegative r on every iteration; termination gives 0≤r<y. Hence the listed postcondition x=qy+r and r<y is B; the full invariant also supplies the nonnegative lower bound.

Original paper, page 25 · Answer key

2 marks · NAT
Report issue

Control Flow & Loop Tracing

Question 53, GATE 2015: How many times is printf executed in this C program?
#include <stdio.h>
int main() {
 int i,j,k=0;
 j=2*3/4+2.0/5+8/5;
 k-=--j;
 for(i=0;i<5;i++) {
  switch(i+k) {
   case 1:
   case 2: printf("\n%d",i+k);
   case 3: printf("\n%d",i+k);
   default: printf("\n%d",i+k);
  }
 }
 return 0;
}
There are no break statements.
Tap to enlarge
Answer & solution

Official answer: 10

1. Integer division gives 2*3/4=1 and 8/5=1; adding 2.0/5 produces 2.4, converted to int j=2.

2. Then k-=--j sets j=1 and k=−1. For i=0, 1, 2, 3, 4 the switch values are−1, 0, 1, 2, 3. With no breaks, the numbers of printf executions are 1, 1, 3, 3, 2, totaling 10. Case1 falls into case2 without printing itself.

Original paper, page 74 · Answer key

1 mark · NAT
Report issue

Control Flow & Loop Tracing

Question 10, GATE 2014: For the C function int func(int num){int count=0; while(num){count++; num>>=1;} return count;}, find func(435).
Tap to enlarge
Answer & solution

Official answer: 9

1. Set up the reasoning. The input is positive, so repeated right shifts discard low bits until the most significant 1 has also been shifted away. The return value is binary length, not population count.

2. Derive the result. For positive num, each right shift divides by 2 and discards the remainder. The sequence 435, 217, 108, 54, 27, 13, 6, 3, 1 has 9 nonzero values before 0, so the loop returns 9.

3. Check the interpretation. Since 28≤435<29, exactly nine shifts are needed. This gives a compact independent check of the explicit sequence and avoids confusing shifts-to-zero with the number of set bits.

Original paper, page 31 · Answer key

2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 42, GATE 2014: A sorted ascending array listA has n>0 entries. ProcessArray sets i=0,j=n−1, then repeatedly sets k=(i+j)/2 using integer division; if x≤listA[k], sets j=k−1; independently, if listA[k]≤x, sets i=k+1; repeats while i≤j. Afterward returns k if listA[k]==x, else −1. Which is correct? A absent x causes an infinite loop; B this is binary search; C it always finds the maximum; D it returns −1 even when x is present.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Step 1: If x is smaller than the midpoint, only the first comparison succeeds, eliminating the midpoint and upper half. If x is larger, only the second succeeds, eliminating the lower half. Each unsuccessful iteration strictly shrinks the candidate interval. Step 2: If x equals the midpoint, both independent tests succeed: j=k−1 and i=k+1. The loop terminates immediately, and the final equality test returns the matching k. Step 3: Therefore it implements binary search, B, including for duplicates where any matching index suffices. Assume a valid nonempty sorted array and arithmetic without overflow in i+j.

Original paper, page 63 · Answer key

2 marks · MCQ
Report issue

Returned value of nested loops

Control Flow & Loop Tracing

Question 31, GATE 2013: For integer n, unknown initializes k=0; for i=n/2 through n inclusive, for j=2 while j≤n doubling each time, it adds n/2 to k; finally returns k. Choose growth of returned value: AΘ(n²), BΘ(n²log n), CΘ(n³), DΘ(n³log n). Integer divisions truncate; asymptotics use no-overflow mathematical arithmetic.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

The outer loop runs Θ(n) times and the doubling inner index takes Θ(log n) iterations for each. Each iteration adds a value Θ(n) to the accumulator. Thus the returned value is Θ(n² log n), B. The number of loop-body executions, and hence the usual unit-cost running time, is only Θ(n log n); the question asks for the value returned. This asymptotic calculation uses mathematical integers or assumes no integer overflow, rather than literal fixed-width C behavior for arbitrarily large n.

There are n−floor(n/2)+1 outer iterations. For n≥2 the inner values are 2, 4,…, 2^floor(log2 n), so there are floor(log2 n) inner iterations each time. Each contributes floor(n/2), giving the exact mathematical-integer value [n−floor(n/2)+1]floor(log2 n)floor(n/2). Multiplying these three orders gives Θ(n²log n). A running-time answer would omit the magnitude added per iteration and would be a different question.

Original paper, page 7 · Answer key

1 mark · MCQ
Report issue

Switch fall-through and escape sequences

Control Flow & Loop Tracing

Question 3, GATE 2012: What will be the output of the following C program segment?

       char inChar = ‘A’ ;
       switch ( inChar ) {
       case ‘A’ : printf (“Choice A\ n”) ;
       case ‘B’ :
       case ‘C’ : printf (“Choice B”) ;
       case ‘D’ :
       case ‘E’ :
       default : printf ( “ No Choice” ) ; }
       (A) No Choice
       (B) Choice A
       (C) Choice A
            Choice B No Choice
       (D) Program gives no output as it is erroneous
Tap to enlarge
Your answer
Answer & solution

Official answer: Marks to All

Our answer: C under intended newline interpretation

If the first printf is interpreted as the intended standard newline escape \n, execution enters case A and falls through every following label because there is no break. It prints Choice A, a newline, then Choice B and No Choice, matching C. The printed source visibly separates the backslash and n in the first string; taking backslash-space literally is not the standard newline escape and does not justify an unconditional portable-output answer. The official key awards Marks to All. This is an independently observed printing/interpretation concern, not a claim about the authority’s reason.

Check: Switch labels are entry points, not implicit stopping points. After executing the case-A printf, the empty B label passes through to C’s printf; D and E are also empty, so execution reaches default’s printf before leaving the switch.

Original paper, page 2 · Answer key

2 marks · MCQ
Report issue

Nontermination in a binary-search implementation

Control Flow & Loop Tracing

Question 84, GATE 2008: This erroneous historical C binary-search function uses integer division:
1. f(int Y[10], int x) {
2.   int i,j,k;
3.   i=0; j=9;
4.   do {
5.     k=(i+j)/2;
6.     if(Y[k]<x) i=k; else j=k;
7.   } while((Y[k]!=x) && (i<j));
8.   if(Y[k]==x) printf("x is in the array");
9.   else printf("x is not in the array");
10. }
For which input does it fail?

(A) Y=[1,2,3,4,5,6,7,8,9,10], x<10
(B) Y=[1,3,5,7,9,11,13,15,17,19], x<1
(C) Y=[2,2,2,2,2,2,2,2,2,2], x>2
(D) Y=[2,4,6,8,10,12,14,16,18,20], 2<x<20 and x even
Question 84, GATE 2008: This erroneous historical C binary-search function uses integer division:
1. f(int Y[10], int x) {
2.   int i,j,k;
3.   i=0; j=9;
4.   do {
5.     k=(i+j)/2;
6.     if(Y[k]<x) i=k; else j=k;
7.   } while((Y[k]!=x) && (i<j));
8.   if(Y[k]==x) printf("x is in the array");
9.   else printf("x is not in the array");
10. }
For which input does it fail?

(A) Y=[1,2,3,4,5,6,7,8,9,10], x<10
(B) Y=[1,3,5,7,9,11,13,15,17,19], x<1
(C) Y=[2,2,2,2,2,2,2,2,2,2], x>2
(D) Y=[2,4,6,8,10,12,14,16,18,20], 2<x<20 and x even
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. With all entries equal to 2 and x>2, every comparison takes i=k. The interval evolves (i,j)=(0,9)→(4,9)→(6,9)→(7,9)→(8,9), then k remains 8 forever.
2. Y[k]≠x and i<j both stay true, so the program fails to terminate, option C. For A, all integer keys below 10 that are present (1 through 9) can be found and keys below 1 terminate as absent; B also shrinks j to zero and terminates absent; D contains only present even values strictly between its endpoints.

Original paper, page 18

2 marks · MCQ
Report issue

Repairing the erroneous binary search

Control Flow & Loop Tracing

Question 85, GATE 2008: This erroneous historical C binary-search function uses integer division:
1. f(int Y[10], int x) {
2.   int i,j,k;
3.   i=0; j=9;
4.   do {
5.     k=(i+j)/2;
6.     if(Y[k]<x) i=k; else j=k;
7.   } while((Y[k]!=x) && (i<j));
8.   if(Y[k]==x) printf("x is in the array");
9.   else printf("x is not in the array");
10. }
Which correction makes the program work properly?

(A) Replace line 6 with if(Y[k]<x) i=k+1; else j=k−1;
(B) Replace line 6 with if(Y[k]<x) i=k−1; else j=k+1;
(C) Replace line 6 with if(Y[k]<=x) i=k; else j=k;
(D) Replace line 7 with } while((Y[k]==x) && (i<j));
Question 85, GATE 2008: This erroneous historical C binary-search function uses integer division:
1. f(int Y[10], int x) {
2.   int i,j,k;
3.   i=0; j=9;
4.   do {
5.     k=(i+j)/2;
6.     if(Y[k]<x) i=k; else j=k;
7.   } while((Y[k]!=x) && (i<j));
8.   if(Y[k]==x) printf("x is in the array");
9.   else printf("x is not in the array");
10. }
Which correction makes the program work properly?

(A) Replace line 6 with if(Y[k]<x) i=k+1; else j=k−1;
(B) Replace line 6 with if(Y[k]<x) i=k−1; else j=k+1;
(C) Replace line 6 with if(Y[k]<=x) i=k; else j=k;
(D) Replace line 7 with } while((Y[k]==x) && (i<j));
Question 85, GATE 2008: This erroneous historical C binary-search function uses integer division:
1. f(int Y[10], int x) {
2.   int i,j,k;
3.   i=0; j=9;
4.   do {
5.     k=(i+j)/2;
6.     if(Y[k]<x) i=k; else j=k;
7.   } while((Y[k]!=x) && (i<j));
8.   if(Y[k]==x) printf("x is in the array");
9.   else printf("x is not in the array");
10. }
Which correction makes the program work properly?

(A) Replace line 6 with if(Y[k]<x) i=k+1; else j=k−1;
(B) Replace line 6 with if(Y[k]<x) i=k−1; else j=k+1;
(C) Replace line 6 with if(Y[k]<=x) i=k; else j=k;
(D) Replace line 7 with } while((Y[k]==x) && (i<j));
Tap to enlarge
Your answer
Answer & solution

Answer: No fully correct option; A repairs the update but is incomplete (no official key was published)

1. Option A changes the bounds to i=k+1 or j=k−1, removing the nonprogress bug in Q84. But line 7 still tests i<j, so it can stop before examining a remaining singleton. Counterexample: Y=[1,2,3,4,5,6,7,8,9,10], x=4.
2. With A, k=4 gives j=3; k=1 gives i=2; k=2 gives i=3. Now i=j=3, so the loop exits and wrongly reports absent because its last examined value was Y[2]=3. A complete repair also changes the continuation bound to i<=j (while retaining the found test), or rewrites the usual while(i<=j) search.
3. B expands bounds, C still stalls on many absent keys, and D continues on equality instead of inequality. Thus A is the likely intended correction, but none alone makes the displayed program generally correct.

Original paper, page 18

1 mark · MCQ
Report issue

Loop-condition comparison count

Control Flow & Loop Tracing

Question 15, GATE 2007: Consider the C fragment:
int j, n;
j = 1;
while (j <= n)
    j = j * 2;
For n>0, how many comparisons are made during execution? The printed choices are below; note the distinction between successful comparisons and the final failing test.
Options:
(A) ceil(log₂ n)+1
(B) n
(C) ceil(log₂ n)
(D) floor(log₂ n)+1
Tap to enlarge
Your answer
Answer & solution

Answer: floor(log2 n)+2 including the final failed test; no exact listed option (no official key was published)

1. Approach. Let k=floor(log₂ n). The successful tests use j=20 through 2k. Then the loop tests 2k+1 once and fails. Check n=1 as a quick boundary example: two tests, one iteration.

2. Derivation and interpretation. Assume n is supplied positive and arithmetic does not overflow. The loop condition is tested with j=1,2,4,...,2^floor(log2 n), all successful, then once more at 2^(floor(log2 n)+1), which fails. Thus body executions and successful comparisons number floor(log2 n)+1, but all comparisons number floor(log2 n)+2. Option D counts successful tests/body executions only. The fragment declares n without assigning it; the question’s n>0 premise must supply its value, and literal fixed-width C may also overflow for large n. No official key is inferred.

Original paper, page 4

1 mark · MCQ
Report issue

Value accumulated during repeated halving

Control Flow & Loop Tracing

Question 15, GATE 2006: For positive integer n, the C fragment is: for (i=n,j=0; i>0; i/=2,j+=i); . Here i,j,n are integer variables and the loop body is empty. Which is the asymptotic value of j after termination, rather than the running time?
Options:
(A) Θ(log n)
(B) Θ(√n)
(C) Θ(n)
(D) Θ(n log n)
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. The update uses the comma operator: first integer-divide i by 2, then add the new i to j. For positive n, j=floor(n/2)+floor(n/4)+...=n−popcount(n).

2. It is at least floor(n/2) and less than n, hence Θ(n), C. This is the value accumulated, not the Θ(log n) iteration count.

3. Its value remains below n, so no positive signed overflow is needed when n is representable.

4. Teaching check: For n=13 the updates add 6,3,1,0, yielding j=10 even though there are only four iterations. Generally the sum lies between floor(n/2) and n, which supplies matching linear bounds without needing the exact popcount identity.

Original paper, page 2

2 marks · MCQ
Report issue

Merge-loop postconditions and output index

Control Flow & Loop Tracing

Question 53, GATE 2006: Sorted integer arrays a[0…n−1],b[0…m−1] have positive lengths. Array c has capacity n+m. Execute:
i=j=k=0;
while (i<n && j<m) {
  if (a[i]<b[j]) c[k++]=a[i++];
  else c[k++]=b[j++];
}
Which printed postcondition is valid?
I: if i=n, then j<m, k=n+j−1, and a[n−1]<b[j].
II: if j=m, then i<n, k=m+i−1, and b[m−1]≤a[i].
The −1 terms are retained exactly as reproduced in both sources.
Options:
(A) Only I
(B) Only II
(C) Either I or II, but not both
(D) Neither I nor II
Question 53, GATE 2006: Sorted integer arrays a[0…n−1],b[0…m−1] have positive lengths. Array c has capacity n+m. Execute:
i=j=k=0;
while (i<n && j<m) {
  if (a[i]<b[j]) c[k++]=a[i++];
  else c[k++]=b[j++];
}
Which printed postcondition is valid?
I: if i=n, then j<m, k=n+j−1, and a[n−1]<b[j].
II: if j=m, then i<n, k=m+i−1, and b[m−1]≤a[i].
The −1 terms are retained exactly as reproduced in both sources.
Options:
(A) Only I
(B) Only II
(C) Either I or II, but not both
(D) Neither I nor II
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. The loop starts i=j=k=0. Each iteration increments exactly one of i,j and also k, preserving k=i+j.

2. At termination, if i=n then j<m and k=n+j; the final extraction from a implies a[n−1]<b[j]. If j=m then i<n and k=m+i; the final extraction from b implies b[m−1]≤a[i].

3. Both printed assertions instead give k one less than these values. Hence neither assertion is correct: D.

4. This uses positive array lengths and defined array accesses, as intended by the example.

6. Teaching check: Initially k=i+j=0. Every loop iteration increments k and exactly one of i,j, so k=i+j remains true. At exit, replacing i by n or j by m yields k=n+j or k=m+i, directly contradicting the printed −1 regardless of the final comparison.

Original paper, page 7

2 marks · MCQ
Report issue

Invariant for reversing decimal digits

Control Flow & Loop Tracing

Question 32, GATE 2004: An input nonnegative integer has original digits d1 d2 … dm. The fragment is:
int n, rev; /* n contains the input */
rev=0;
while(n>0) {
  rev=rev*10+n%10;
  n=n/10;
}
Which invariant holds after iteration i? Assume integer division and no overflow; digit strings denote numeric values.
Options:
(A) n=d1…d_(m−i) AND rev=d_m d_(m−1)…d_(m−i+1)
(B) n=d_(m−i+1)…d_(m−1)d_m OR rev=d_(m−i)…d2 d1
(C) n≠rev
(D) n=d1 d2…d_m OR rev=d_m…d2 d1
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. After i iterations, n is the original prefix d1...dm−i, and rev is the processed suffix in reverse order dm dm−1...dm−i+1, A. Each step removes n’s final digit and appends it to rev.

2. The notation describes numeric digit values, so leading zeros in the reversed suffix do not change the value; assume the input is supplied nonnegative and the reversed value fits int.

3. Teaching check: For input 1234, successive (n,rev) pairs are (123,4),(12,43),(1,432),(0,4321). This verifies both halves of the invariant simultaneously. An OR condition that merely describes the initial or final arrangement does not express the state after every iteration.

Original paper, page 4

2 marks · MCQ
Report issue

Subtractive Euclidean algorithm

Control Flow & Loop Tracing

Question 41, GATE 2004: What does this C-style fragment compute for positive integers x,y?
m=x; n=y;
while(m!=n) {
  if(m>n) m=m-n;
  else n=n-m;
}
printf("%d",n);
GFG option A is division by repeated subtraction; GateForum prints x+y instead.
Options:
(A) x/y by repeated subtraction
(B) x mod y by repeated subtraction
(C) Greatest common divisor of x,y
(D) Least common multiple of x,y
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. For positive x,y, each iteration replaces the larger of m,n by its difference with the smaller. This preserves gcd(m,n), keeps both positive, and strictly decreases m+n until m=n.

2. The printed common value is gcd(x,y). This is not ordinary repeated subtraction for division: the roles of the two operands change.

3. Teaching check: For x=12,y=8, the pairs evolve (12,8)→(4,8)→(4,4), so the answer is 4. Every common divisor is preserved by subtracting one operand from the other. The positive decreasing sum proves termination, completing both partial correctness and progress.

Original paper, page 6

1 mark · MCQ
Report issue

Exponential-series accumulation

Control Flow & Loop Tracing

Question 1, GATE 2003: For large positive integer y, what does this C function approximate?
float f(float x, int y) { float p, s; int i; for(s=1,p=1,i=1; i<y; i++){p*=x/i; s+=p;} return s; }
A. x^y; B. e^x; C. ln(1+x); D. x^x.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. The recurrence for p is p₀=1 and pᵢ=pᵢ₋₁x/i. Induction gives pᵢ=xⁱ/i!. The accumulator includes the initial term 1, so it contains exactly y terms, not y+1. Comparing with the Taylor expansion eˣ=1+x+x²/2!+⋯ identifies the limit.

2. Initially p=1 and s=1. On iteration i, p is multiplied by x/i, so it becomes xi/i!, which is added to s. The returned value is the truncated series sum from i=0 to y−1 of xi/i!, approaching ex for fixed x as y increases. Thus B in the mathematical arithmetic model; finite floating-point range/roundoff can limit the actual approximation.

Original paper, page 1

2 marks · MCQ
Report issue

Logical-OR remainder loop prints no integers

Control Flow & Loop Tracing

Question 88, GATE 2003: In this C fragment j,k,n,TwoLog_n are integers, A is an integer array and n≥3. GFG defines TwoLog_n=2 floor(log2 n); GateForum instead uses 2 ceil(log2 n).
for(k=3;k<=n;k++) A[k]=0;
for(k=2;k<=TwoLog_n;k++)
  for(j=k+1;j<=n;j++)
    A[j]=A[j] || (j%k);
for(j=3;j<=n;j++)
  if(!A[j]) printf("%d ",j);
What set is printed?
A. {m:m≤n and m=i! for some integer i}
B. {m:m≤n and m=i² for some integer i}
C. {m:m≤n and m is prime}
D. ∅
Question 88, GATE 2003: In this C fragment j,k,n,TwoLog_n are integers, A is an integer array and n≥3. GFG defines TwoLog_n=2 floor(log2 n); GateForum instead uses 2 ceil(log2 n).
for(k=3;k<=n;k++) A[k]=0;
for(k=2;k<=TwoLog_n;k++)
  for(j=k+1;j<=n;j++)
    A[j]=A[j] || (j%k);
for(j=3;j<=n;j++)
  if(!A[j]) printf("%d ",j);
What set is printed?
A. {m:m≤n and m=i! for some integer i}
B. {m:m≤n and m=i² for some integer i}
C. {m:m≤n and m is prime}
D. ∅
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. Logical OR leaves A[j]=0 only if every tested remainder j%k is zero. A nonzero remainder permanently sets the entry to 1. This is divisibility by every tested k, not primality testing.
2. Let L=TwoLog_n. For 3≤j≤L+1, the iteration k=j−1 is performed and leaves remainder 1, so none of those j prints.
3. For j>L+1, all k=2,...,L are tested. A printed j would therefore have to be a multiple of M=lcm(1,...,L). The useful bound M≥2L−1 follows because each binomial coefficient C(L−1,k) divides M/L, so summing the L coefficients gives 2L−1≤M.
4. With r=floor(log2 n) and L=2r, for n≥4 we have r≥2, hence M≥22r−1≥2r+1>n. No positive multiple can lie in the printing range. For n=3, k=2 marks 3 directly.
5. Nothing prints, D. The ceiling variant has at least the same tests, so also cannot print anything.

Solution: A[j] becomes true as soon as one tested k does not divide j; this is not a sieve that marks multiples. Let L be the outer-loop limit. If 3≤j≤L+1, the tested k=j−1 leaves remainder one, so j is not printed. For j>L+1, printing requires j to be divisible by every integer from 2 through L, hence by lcm(1,…,L). Let r=floor(log2 n), L=2r. For n≥4, the standard bound lcm(1,…,L)≥2L−1=22r−1≥2r+1>n rules this out. The n=3 case is directly marked by k=2. Thus nothing is printed, D. The LCM bound can also be established from the fact that every binomial coefficient in row L−1 divides lcm(1,…,L)/L, whose row sum is 2L−1.

Original paper, page 13

5 marks · Descriptive
Report issue

Failure conditions of a binary search

Control Flow & Loop Tracing

Question 18, GATE 1996: For N>1, the following Pascal-like program searches an array a[1..N]: initialize i=1,j=N; repeatedly set k=floor((i+j)/2), then if a[k]<x set i=k, otherwise set j=k; stop when a[k]=x or i>=j. Finally print success if a[k]=x and failure otherwise. Determine when it fails. For the intended binary-search interpretation assume a is sorted in nondecreasing order. GFG prints the success message correctly; GateForum instead prints failure in both final branches.
Question 18, GATE 1996: For N>1, the following Pascal-like program searches an array a[1..N]: initialize i=1,j=N; repeatedly set k=floor((i+j)/2), then if a[k]<x set i=k, otherwise set j=k; stop when a[k]=x or i>=j. Finally print success if a[k]=x and failure otherwise. Determine when it fails. For the intended binary-search interpretation assume a is sorted in nondecreasing order. GFG prints the success message correctly; GateForum instead prints failure in both final branches.
Tap to enlarge
Answer & solution

Answer: It loops when x>a[1] and x is not in positions 1..N−1; in particular a unique match at the last element is missed (no official key was published)

The defect is that the lower update keeps the already examined element: i=k instead of i=k+1. When j=i+1, integer division gives k=i. If a[i]<x, setting i=k changes nothing; j also stays unchanged, a[k] is not x, and i<j remains true. The loop repeats forever.

In fact the final array position N is never examined: while i<j, floor((i+j)/2)<j<=N, so k<=N−1. On a nondecreasing array, the exact classification is: every x occurring among a[1],...,a[N−1] is eventually found; every x<a[1] terminates with failure; every x>a[1] absent from a[1..N−1] loops forever. The latter includes absent values between array entries, values above the maximum, and x=a[N] when that value occurs only at the last position. Duplicates matter: x=a[N] is found if the same value occurs earlier.

For example a=[1,3], x=3 gives (i,j,k)=(1,2,1) forever. With x=0, the first iteration instead sets j=1 and terminates correctly. For a=[1,3,5], x=3 is examined immediately and succeeds. These examples distinguish the actual bug from the inaccurate claim that all unsuccessful searches fail.

A robust repair uses while i<=j, tests equality first, then sets i=k+1 when a[k]<x and j=k−1 otherwise, reporting failure after the interval becomes empty. This also permits examining N.

Original paper, page 9

5 marks · Descriptive
Report issue

Completing a four-bit two’s-complement conversion

Control Flow & Loop Tracing

Question 18, GATE 1995: Complete blanks A, B, C in this Pascal-like function, for integer −8≤N≤7: if N<0 then N:=A; BINARY:=0; EXPONENT:=1; while N<>0 do begin REM:=N mod 2; BINARY:=BINARY+B*EXPONENT; EXPONENT:=EXPONENT*10; N:=C end; TWOSCOMP:=BINARY. REM, EXPONENT and BINARY are integer variables. The returned decimal integer has the binary digits as its decimal digits. GFG declares REM; GateForum declares RAM but uses REM.
Question 18, GATE 1995: Complete blanks A, B, C in this Pascal-like function, for integer −8≤N≤7: if N<0 then N:=A; BINARY:=0; EXPONENT:=1; while N<>0 do begin REM:=N mod 2; BINARY:=BINARY+B*EXPONENT; EXPONENT:=EXPONENT*10; N:=C end; TWOSCOMP:=BINARY. REM, EXPONENT and BINARY are integer variables. The returned decimal integer has the binary digits as its decimal digits. GFG declares REM; GateForum declares RAM but uses REM.
Tap to enlarge
Answer & solution

Answer: A=N+16; B=REM; C=N div 2. (no official key was published)

Four bits represent signed values from −8 to 7. A negative N has the same four-bit pattern as the unsigned residue N+24=N+16. Thus the first blank is N+16: −8 maps to 8 (1000), and −1 maps to 15 (1111). Nonnegative inputs need no conversion before digit extraction.

For a nonnegative integer, N mod 2 is its least significant binary digit. The current EXPONENT is 1,10,100,1000, so adding REM*EXPONENT puts that bit in the corresponding decimal digit position of the returned integer. Hence B is REM. Integer division N div 2 discards the extracted bit; hence C is N div 2, not real division. Each iteration reduces the nonzero quotient and the loop terminates.

For N=−3, convert to 13. The remainders are 1,0,1,1, the accumulating decimal result is 1,1,101,1101, and the quotients are 6,3,1,0. Thus the result 1101 denotes the correct four-bit pattern. N=0 skips the loop and returns 0; positive outputs omit leading zero digits because they are stored as integers. Displaying exactly four bits requires zero-padding separately. Outside the guarded range the printed function does not assign its return value.

Original paper, page 7

2 marks · Descriptive
Report issue

Replacing a Boolean conditional assignment

Control Flow & Loop Tracing

Question 4(i), GATE 1991: Replace Pascal if x>5 then y:=true else y:=false with one assignment.
Question 4(i), GATE 1991: Replace Pascal if x>5 then y:=true else y:=false with one assignment.
Tap to enlarge
Answer & solution

Answer: y := (x > 5); (no official key was published)

The comparison x>5 evaluates to a Boolean. In the true case, the original statement assigns true to y; in the false case, it assigns false. Assigning the comparison result therefore gives exactly the same value in both cases. At x=5, the result is false, so using ≥ instead would be incorrect. This simplification assumes y has Boolean type and the comparison has the ordinary Pascal semantics shown in the source. No branch or numeric Boolean encoding is needed.

Original paper, page 5

2 marks · Descriptive
Report issue

Converting repeat-until to while

Control Flow & Loop Tracing

Question 4(ii), GATE 1991: Rewrite Pascal repeat S until B using a while construct with equivalent behavior.
Question 4(ii), GATE 1991: Rewrite Pascal repeat S until B using a while construct with equivalent behavior.
Tap to enlarge
Answer & solution

Answer: begin S; while not B do S end (no official key was published)

A repeat loop executes S before checking B, so S runs at least once. Execute S once explicitly, then test not B in the while guard. Whenever B remains false, execute S again; stop immediately after an iteration makes B true. Merely writing while not B do S would incorrectly permit zero executions when B starts true. This transformation preserves the sequence of evaluations of B after executions of S, including ordinary side effects in the condition. If S is a multi-statement sequence, it must be grouped as a Pascal compound statement.

Original paper, page 5