Programming in C

GATE CS previous year questions · 3 questions

GATE CS 2025 Set 2 | Question 33

NAT · 1 mark
int x=126,y=105;
do {
    if(x>y) x=x-y;
    else y=y-x;
} while(x!=y);

printf("%d",x);

The output of the given C code segment is ________. (Answer in integer)

Explanation

Answer: 21

The loop is the subtraction form of Euclid’s algorithm. Replacing the larger number by the difference of the two never changes their greatest common divisor, and the values keep shrinking until they are equal, so both end up as \(\gcd(126, 105)\).

Trace of \((x, y)\): \((126, 105) \to (21, 105) \to (21, 84) \to (21, 63) \to (21, 42) \to (21, 21)\). Now x!=y is false, the do-while loop exits and 21 is printed.

Answer: 21

GATE CS 2024 Set 1 | Question 18

MCQ · 1 mark · −0.33

Consider the following C program:

#include <stdio.h>
int main(){
   int a = 6;
   int b = 0;
   while(a < 10) {
      a = a / 12 + 1;
      a += b;}
   printf("%d", a);
   return 0;}

Which one of the following statements is CORRECT?

Options for GATE CS 2024 Set 1 | Question 18

Explanation

Answer: (C)

Both operands of a / 12 are integers, so the division truncates. Starting from a = 6, the first pass gives \(6/12 = 0\), so a becomes \(0 + 1 = 1\), and a += b adds 0.

On every later pass a is 1: the test \(1 < 10\) holds, \(1/12 = 0\), and a is set to 1 again. Since b stays 0, nothing ever raises a to 10, so the condition never fails, the loop never exits and printf is never reached.

Options A, B and D all assume that the loop ends and something is printed.

Answer: C

GATE CS 2024 Set 1 | Question 48

MSQ · 2 marks

Consider the following C function definition.

int f(int x, int y) {
  for (int i=0; i<y; i++) {
    x=x+x+y;
  }
  return x;
}

Which of the following statements is/are TRUE about the above function?

Options for GATE CS 2024 Set 1 | Question 48

Explanation

Answer: (B), (D)

Each iteration sets \(x \leftarrow 2x + y\), and the loop runs \(y\) times. Adding \(y\) to both sides shows that \(x + y\) doubles on every iteration, so the function returns \(2^{y}(x + y) - y\).

  • x=20, y=10: \(2^{10} \cdot 30 - 10 = 30710\). That is below \(2^{20} = 1048576\) but above \(2^{10} = 1024\), so A and C are false.
  • x=20, y=20: \(2^{20} \cdot 40 - 20 = 41943020 \gt 2^{20}\), so B is true.
  • x=10, y=20: \(2^{20} \cdot 30 - 20 = 31457260 \gt 2^{20}\), so D is true.

Both large results are below \(2^{31} - 1\), so int does not overflow.

Answer: B, D