In: Computer Science
Java Program
1. Write a program that asks the user: “Please enter a number (0 to exit)”. Your program shall accept integers from the user (positive or negative), however, if the user enters 0 then your program shall terminate immediately. After the loop is terminated, return the total sum of all the previous numbers the user entered.
a. What is considered to be the body of the loop?
b. What is considered the control variable?
c. What is considered to be the test?
d. What is considered to be the update?
e. How can you incorporate the sentinel component into the test?
f. How can you calculate the sum of all previous numbers?
g. Which kind of loop do you think is more convenient to use? And why?
h. Construct the loop based on the information you collected
a.The statements inside the braces followed by the 'do' keyword are body of the loop
b. The user input 'n' is the control variable
c. The user input 'n' is the test
d. When we take the user input, it is the input
e. Sentinal component in the test is during the user input, when the data is updated for`
f. After each input, the value of the sum is updated by adding the value of user input
g. A do while loop is the most convenient to use, since we don't know how many times we need to repeat the process.
h. Code:
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int sum = 0;
double n;
do{
//body of the loop
System.out.print("Please enter a number (0 to exit) : ");
n = sc.nextDouble();//update the value
sum += n;//calculating the sum of the input values
}while(n!=0);//n is the control variable
System.out.println("The sum is : "+sum);
}
}
Output:
Code Screenshot: