In this tutorial, we are going to learn a writing the java program to find the average of numbers using while loop.
In previous tutorial we have seen the different way to find Average of number
- Java Program to calculate Average Input taken by user.
- Java Program to calculate Average of Integer Array.
Problem Statement
For any sequence of input numbers, we have to calculate the average of the input numbers from the user using the while loop.
Case1: If the Input sequence given by user are 1,2,3,4,5.
The output should be 3.
Case2: If the Input Sequence given by user are 11,22,33,44,55,66.
The output should be 38.5.
Our Logic to calculate average using while loop in java
- Our program will declare the variable sum =0, i=0 and also the array is predefined at the beginning.
- Then. Our program will calculate the sum of all the numbers using ‘while loop’.
- Finally, the calculated sum is then divided by the number of elements present in the array (or length of array) and print the result as the output.
Algorithm to calculate average of the numbers using while loop
Step 1: Start
Step 2: float sum =0;
Step 3: Scanner sc = new Scanner(System.in);
Step 4: input array size
int n= sc.nextInt();
Step 5: create an empty array of size n.
Step 6: while (i < n) {
arr[i] = sc.nextInt();
sum=sum+arr[i];
i++;
}
Step 7: assign a variable, avg as float
average = sum/n;
Step 8: print average
Step 9: Stop
Find Average of numbers using while loop in Java
import java.util.*;
public class Main
{
public static void main(String[] args) {
int i=0;
float sum=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array: ");
int n = sc.nextInt();
float arr[] = new float[n];
System.out.println("Enter " + n + " array elements: ");
while(i<n) {
arr[i] = sc.nextInt();
sum=sum+arr[i];
i++;
}
float average = sum/n;
System.out.println("Average of number is : "+average);
}
}
Output
Enter the size of array:
5
Enter 5 array elements:
4
5
3
6
4
Average of number is : 4.4
Explanations
In this example, the predefined array are {2,4,6,8,10}. Where the size of array is 5 so the average will be
Average = (2+4+6+8+10)/ 5
The output generated is 6.0.