Write a program that asks the user for a positive nonzero integer value which is
ID: 3673707 • Letter: W
Question
Write a program that asks the user for a positive nonzero integer value which is stored in variable N. (Input Validation: keep asking the user until he enters a valid one). With a valid input, do the following using separate loops. The program should use a For Loop to get the sum of all the integers from 1 up to N and finally calculate the average. For example: if the user enters 10, the loop will find the sum of 1,2,3,4...10 and then compute the average. In another For Loop, compute the sum of all even numbers and odd numbers in from 1 up to N and also calculate the averages of even set and odd set. For example, if N is 10, sum Even is sum of 2,4,6...10 and average Even is its average value. Sum Odd is sum of 1,3,5...9 and average Odd is its average value.Explanation / Answer
public class ComputeAverage { public static void main(String[] args) { int inputNumber; // One of the integers input by the user. int sum; // The sum of the positive integers. int count; // The number of positive integers. double average; // The average of the positive integers. /* Initialize the summation and counting variables. */ sum = 0; count = 0; /* Read and process the user's input. */ System.out.print("Enter your first positive integer: "); inputNumber = TextIO.getlnInt(); while (inputNumber != 0) { sum += inputNumber; // Add inputNumber to running sum. count++; // Count the input by adding 1 to count. System.out.print("Enter your next positive integer, or 0 to end: "); inputNumber = TextIO.getlnInt(); } /* Display the result. */ if (count == 0) { System.out.println("You didn't enter any data!"); } else { average = ((double)sum) / count; System.out.println(); System.out.println("You entered " + count + " positive integers."); System.out.printf("Their average is %1.3f. ", average); } } // end main() } // end class ComputeAverage
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.