The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
+17 votes

Consider the C program fragment below which is meant to divide $x$ by $y$ using repeated subtractions. The variables $x$, $y$, $q$ and $r$ are all unsigned int.

while (r >= y) {

Which of the following conditions on the variables $x, y, q$ and $r$ before the execution of the fragment will ensure that the loop terminated in a state satisfying the condition $x==(y*q + r)$?

  1. $(q==r) \ \&\& \ (r==0)$
  2. $(x>0) \ \&\&  \ (r==x) \ \&\& \ (y>0)$
  3. $(q==0) \ \&\& \ (r==x) \ \&\& \ (y >0)$
  4. $(q==0) \ \&\& \ (y>0)$
in Programming by Veteran (416k points)
edited by | 3.3k views

5 Answers

+27 votes
Best answer

Here, $x == ( y*q + r )$ says $q =$ quotient and $r =$  remainder.

To divide a number with repeated subtraction, quotient should be initialized to $0$ and should be incremented for each subtraction.

Initially $q=0 \Rightarrow r = x$.

$\therefore$ Initial conditions should be C] $(q == 0) \ \&\& \ (r == x) \ \&\& \ (y > 0)$.

by Active (4.5k points)
edited by
why do we need to check y>0 despite of it is given that y is unsigned integer.

If we divide a number with 0 (zero), will result in undefined state. that's why we need to check y > 0 condition. And one more point unsigned integer range is 0 to 2n-1.

nice explanation @kantikumar
why quotient take 0 i dont understand plz clear??
take an example x=2, y=3 then x divides y mean quotient q=0,remainder r=2 it becomes x, (r==x) and y is a divisor ,so it should be >0 otherwise whole expression will tend to infinity.
now i got the point thanku
this is a repeated question
how it is knows that the initial condition as r=x?
nice explanaion....
+3 votes
option c
by (147 points)
Why not option d? because when q==0 && y>0, it automatically means x==r, then why mention it explicitly?Please explain
How it automatically means x == r ??
x=(y*q+r) So, when q==0 and y>0 , then x=r...
It is given in the question that we've to satisfy the condition x==(y∗q+r)
It is not given x=(y*q+r)
In the code fragment, initial value of r and q is not set. So, we've to initialize those.
r = x and q = 0.
Thankyou... i understood..
+3 votes

we can solve  by leting some values, as shown below:-

by (219 points)
0 votes

answer is C

by (221 points)
0 votes
Just substitute the values in the variables.

let r=3, y>0 i.e,1 etc and q=0 and substitute in the each options then which one satisfied that is the answer.
by (11 points)

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
49,845 questions
54,784 answers
80,435 users