Skip to content
Official PYQ · 2015

GATE CS 2015 Set 1 Q33 — Programming in C

Explain with AI

Consider the following pseudo code, where xx and yy are positive integers.

begin 
    q := 0 
    r := x 
   while r ≥ y do 
      begin 
      r := r - y 
      q := q + 1 
    end 
end

The post condition that needs to be satisfied after the program terminates is

Choose one option
View worked solution

Answer: B

The given pseudocode implements the standard integer division algorithm to divide a positive integer xx by another positive integer yy, where qq represents the quotient and rr represents the remainder.

1. Identifying the Loop Invariant

Before entering the loop, we initialize:

  • q=0q = 0
  • r=xr = x

At this initial state, the relation x=qy+rx = qy + r holds because:

qy+r=(0imesy)+x=xqy + r = (0 imes y) + x = x

In each iteration of the loop, the variables are updated as follows:

  • rnew=r−yr_{\text{new}} = r - y
  • qnew=q+1q_{\text{new}} = q + 1

Let's check if the relation still holds after these updates:

qnewy+rnew=(q+1)y+(r−y)=qy+y+r−y=qy+r=xq_{\text{new}}y + r_{\text{new}} = (q + 1)y + (r - y) = qy + y + r - y = qy + r = x

Since the relation remains unchanged, x=qy+rx = qy + r is a loop invariant.

2. Termination Condition

The loop runs as long as r≥yr \ge y. Therefore, when the loop terminates, the loop condition must become false:

¬(r≥y)  ⟹  r<y\neg(r \ge y) \implies r < y

3. Post-Condition

Upon termination, both the loop invariant and the termination condition must hold simultaneously. Thus, the post-condition is:

{x=qy+r∧r<y}\{x = qy + r \wedge r < y\}

This matches Option B.

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

Published
Report a correction
Keep exploringMore Programming in C questions