Question #4421

Provide two alternatives (1 for loop and 1 while loop) to the loop in fig. 5.12 that does not change the programs output but also does not use a "break" statement. Modify the sample code below to have a single return statement. Prepare all three modifications in a Word document with a discussion as to why using break in this way as well as using multiple return statements is not considered good programming form by most in the field.

Sample Code:

public boolean isTheFirstOneBigger(int num1, int num2)
{
if (num1 > num2)
{
return true;
}

if (num1 <= num2)
{
return false;
}
}

Expert's answer

Variant 1: for loop

public static boolean isTheFirstOneBigger(int num1, int num2){
for(;;)
if(num1&gt;num2)
return true;
else
return false;
}

Variant 2: while loop

public static boolean isTheFirstOneBigger(int num1, int num2){
while(num1&gt;num2)
return true;
return false;
}

Bonus variant (not required)

public static boolean isTheFirstOneBigger(int num1, int num2){
LATEST TUTORIALS
APPROVED BY CLIENTS