Write a program (in Java) that prompts the user to input an integer. Try to find
ID: 3589893 • Letter: W
Question
Write a program (in Java) that prompts the user to input an integer. Try to find a divisor for this integer, if there are no divisors the integer is a prime number, otherwise it is not a prime number.
Given Code:
import java.util.Scanner;
public class Lab5Part3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
int divisor;
System.out.println("Enter an integer greater than 1");
num = input.nextInt();
divisor = num / 2;
while (num % divisor != 0) {
System.out.println("Trying factor " + divisor);
divisor--;
}
if (divisor == 1) {
System.out.print("The input integer " + num + " is a prime number");
} else {
System.out.print("The input integer " + num + " is divisible by " + divisor);
}
}
Answer these questions:
1. What is the loop control variable?
2. What statement initializes the loop control variable?
3. What is the loop condition?
4. What statement updates the loop control variable?
Explanation / Answer
1. What is the loop control variable?
sol: The loop used in the abive program is while loop
The variable which is controlling it is "int divisor;"
2. What statement initializes the loop control variable?
sol: the intialization statement of the loop control variable divisor is "divisor = num / 2;"
3. What is the loop condition?
sol: the while loop condition is "(num % divisor != 0) "
4. What statement updates the loop control variable?
sol: "divisor--;" is the statement which updates the loop control variable
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.