Consider the following Java code and answer the parts of this question. Each lin
ID: 3855865 • Letter: C
Question
Consider the following Java code and answer the parts of this question. Each line has been given a number so we can refer to it if needed.
1 public class Something {
2 public static void main(String[] args) {
3 int inputNumber;
4 int sum;
5 int count;
6 double a;
7 sum=0;
8 count = 0;
9 System.out.print("Enter your first positive integer: ");
10 inputNumber = TextIO.getlnInt();
11 while (inputNumber != 0) {
12 sum += inputNumber;
13 count++;
14 System.out.print("Enter your next positive integer, or 0 to end: ");
15 inputNumber = TextIO.getlnInt();
16 }
17 if (count == 0) {
18 System.out.println("You didn't enter any data!");
19 }
20 else {
21 a = ((double)sum) / count;
22 System.out.println();
23 System.out.println("You entered " + count + " positive integers.");
24 System.out.println("The value of a is "+a);
25 }
26 } // end main()
27 } // end class Something
a. What is happening in lines 7 and 8 above?
b. In line 11 above, why is the condition on the while loop (inputNumber != 0) ?
c. There is an if-statement in lines 17-19 before the output, why is this placed there?
d. What do you think the program above is trying to achieve?
Explanation / Answer
a. What is happening in lines 7 and 8 above?
Ans) The variables sum, count are initialized to zero because sum variable is used for counting sum of given integers and count for counting number of integers.
b. In line 11 above, why is the condition on the while loop (inputNumber != 0) ?
Ans) The condition is checked in loop to repeatedly take input from the user into variable inputNumber and loop terminates once user enters 0 as input.
c. There is an if-statement in lines 17-19 before the output, why is this placed there?
Ans) The variable count == 0 is checked in line 17 to check if user has entered any positive integer(not 0) as input. If user enters 0 as the first input then it will display "you didn't enter any data!".
d. What do you think the program above is trying to achieve?
Ans) the program is meant for getting average from a given set of +ve integers entered by the user. Also it tells how many integers user has entered.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.