Write a program that calculates the average of N integers Th

•Write a program that calculates the average of N integers. The program should prompt the user to enter the value for N and then afterward must enter all N numbers. If the user enters a non-positive value for N, then an exception should be thrown (and caught) with the message “N must be positive.” If there is any exception as the user is entering the N numbers, an error message should be displayed and the user prompted to enter the number again.

Solution

Hi friend, you have not mentioned about programming language.

I have implemented in Java.

import java.util.Scanner;

public class Average {

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);

       int N = 0;

       while( true){

           try{

               // taking user input for N

               System.out.print(\"Enter N value: \");

               N = sc.nextInt();

               if(N <= 0)

                   throw new Exception();

              

               break; // if N has positive value

           }catch(Exception e){

               System.out.println(\"N must be positive\");

           }

       }

       System.out.println(\"Enter \"+N+\" positive integers: \");

       int i=1;

       double sum = 0;

       // reading N i integers

       while(i <= N){

           int x = sc.nextInt();

           sum = sum + x;

           i++;

       }

       // average

       System.out.println(\"Average: \"+(sum/N));

   }

}

/*

Enter N value: -9

N must be positive

Enter N value: 4

Enter 4 positive integers:

3

4

5

6

Average: 4.5

*/

•Write a program that calculates the average of N integers. The program should prompt the user to enter the value for N and then afterward must enter all N numb
•Write a program that calculates the average of N integers. The program should prompt the user to enter the value for N and then afterward must enter all N numb

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site