Wednesday 14 June 2017

Java Code to compute the average of n numbers

Problem:

     Design an algorithm to compute the average of n numbers.

Algorithm:

1. Prompt and read in the number of numbers to find average.
2. Initialize sum for zero numbers
3. While less than n numbers have been summed repeatedly do
      a. read in next number
      b. compute current sum by adding the number read to the most recent sum.
4. Divide the sum by number of numbers to find out average.
4. Write out average of  n numbers.

Solution:

package com.myprograms;

import java.util.Scanner;

public class AverageOfNNumbers {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter how many numbers you want to find average");
int n = s.nextInt();
int sum = 0;
for(int i = 0; i< n; i++){
System.out.println("enter the number");
sum = sum + s.nextInt();
}
System.out.println("the average is " + sum/n);
s.close();
}
}


Output:
enter how many numbers you want to find average
3
enter the number
1
enter the number
2
enter the number
3
the average is2


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...