Consider the following code segment: if (Y<0) {X=-X;Y=-Y;} Z = 0; While (Y>0) {Z=Z+X;Y=-1;} Assume that X,Y and Z are integer variables, and that X and Y have been initialized. which of the following best describes what this code segment does ?
Consider the following code segment: if (Y<0) {X=-X;Y=-Y;} Z = 0; While (Y>0) {Z=Z+X;Y=-1;} Assume that X,Y and Z are integer variables, and that X and Y have been initialized. which of the following best describes what this code segment does ? Correct Answer Sets Z to be the product X*Y
Consider, x = 2 and y = 3
CASE 1:
if (Y<0) // 3<0 (False)
{X=-X;Y=-Y;}
Z = 0; // z becomes 0
While (Y>0) // 3> 0 (true)
{Z=Z+X;Y=-1;} // z = 0 + 2 = 2 , y = 3 - 1 = 2
CASE 2:
(when z = 2, y =2, x = 2)
if (Y<0)
{X=-X;Y=-Y;}
Z = 0;
While (Y>0) //2 > 0 (True)
{Z=Z+X;Y=-1;} // z = 2 + 2 = 4, y = 2 -1 = 1
CASE 3:
if (Y<0)
{X=-X;Y=-Y;}
Z = 0;
While (Y>0) // 1 >0 (True)
{Z=Z+X;Y=-1;} // z = 4 + 2 = 6, y = 1- 1 = 0
CASE 4:
if (Y<0)
{X=-X;Y=-Y;}
Z = 0;
While (Y>0) // 0 > 0(False)
{Z=Z+X;Y=-1;}
Finally, z becomes 6. which is the product of x and y (i.e. 2 * 3= 6)