Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

*in java* A. How many times is the following loop body repeated? What is the out

ID: 3828644 • Letter: #

Question

*in java*

A. How many times is the following loop body repeated? What is the output of the loop?

int i = 0;

while (i < 10) {

  if ((i + 1) % 2 == 0)

System.out.println(i);

i++;

}

B. Convert the following for loop into a do-while loop.

    int sum = 0;

    for (int i = 0; i < 100; i++) {

      sum += i;

}

C. Convert the following if statement using a switch statemen

    // Find interest rate based on year

    if (numOfYears == 7)

      annualInterestRate = 7.25;

    else if (numOfYears == 15)

      annualInterestRate = 8.50;

    else if (numOfYears == 30)

      annualInterestRate = 9.0;

    else {

      System.out.println("Wrong number of years");

      System.exit(0);

    }

Explanation / Answer

A. How many times is the following loop body repeated? What is the output of the loop?
int i = 0;   //i starts at 0.
while (i < 10) {   //This loop continues as long as i < 10.
if ((i + 1) % 2 == 0)   //if the next value of i is even.
System.out.println(i);    //print i.
i++;       //i increments by 1.
}
So, will run for i values of 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
So, the loop body repeats for 10 times.
And the output is: 1, 3, 5, 7, 9.

B. Convert the following for loop into a do-while loop.
int sum = 0;  
for (int i = 0; i < 100; i++) {
sum += i;
}
The do-while equivalent of the loop is:
int sum = 0;
i = 0;
do
{
    sum += i;
    i++;
}while(i < 100)

C. Convert the following if statement using a switch statemen
// Find interest rate based on year
if (numOfYears == 7)
annualInterestRate = 7.25;
else if (numOfYears == 15)
annualInterestRate = 8.50;
else if (numOfYears == 30)
annualInterestRate = 9.0;
else {
System.out.println("Wrong number of years");
System.exit(0);
}
The switch equivalent to if:
switch(numOfYears)
{
    case 7:
            annualInterestRate = 7.25; break;
    case 15:
            annualInterestRate = 8.50; break;
    case 30:
            annualInterestRate = 9.0; break;
    default:
            System.out.println("Wrong number of years");
       System.exit(0);                          
}