What is the output after the following loop terminates?
int number = 25;
int i;
boolean isPrime = true;
for (i = 2; i < number && isPrime; i++) {
if (number % i == 0) {
isPrime = false;
}
}
System.out.println("i is " + i + " isPrime is " + isPrime);
a. i is 5 isPrime is true
b. i is 5 isPrime is false
c. i is 6 isPrime is true
d. i is 6 isPrime is false
d The code tests if number is prime by dividing the number with possible divisors 2, 3, 4, and so on. Initially, isPrime is set to true. Once a divisor is found (i.e., number % i == 0 is true), isPrime is set to false. The loop continuation condition now becomes false. The loop ends. If no divisor is found after the loop is finished, isPrime remains true. Since number is 25, number % i == 0 is true when i is 5 . In this case, isPrime is set to false and i++ increments i by 1 in the action-after-each-iteration. So, the output is that i is 6 and isPrime is false. The correct anwer is D.
You might also like to view...
A byte refers to a single binary state of on or off
Indicate whether the statement is true or false
A mandatory furlough provides the organization with the ability to audit the work of an individual. _________________________
Answer the following statement true (T) or false (F)