by Dinesh Thakur Category: Control Structures

In this example, we input number of elements n (i.e.) whose average is to be calculated. When for loop begins executing, the loop control variable i is declared and initialized to 1. Then the test condition (i<=n) is checked. As it is true in this case because (1<=5) and the statements in the body of the loop are executed which inputs the first number (5 in our case) and add this value to variable sum. Then the increment expression i++ increases the value of variable i by 1 (i+ 1=2). After one complete iteration, the test condition in the for loop is checked again which is true again as (2<=5) and the body of the loop is executed again. This process continues until the loop control variable (i) is incremented to 6. Now when the test condition (6<=5) is evaluated again it becomes false and the execution of for loop terminates and control transfers to the next statement following the for loop that calculates the average of n (5) numbers which is then displayed.

The type casting is needed in this program so that fractional part of average of n numbers is not ignored.

//Java Program to Find Average of N Numbers

import java.util.Scanner; //Program uses Scanner class
public class Average
     public static void main(String[] args)
        int n,num,sum=0, i;
        //create scanner object to obtain input from keyboard
        Scanner input =new Scanner(;
        System.out.print("Enter How Many Numbers : ");//input
        n =input.nextInt(); //read total numbers
        System.out.print("Enter the Numbers :");
        for(i=1;i<=n; i++)
                 num=input.nextInt(); //input number
                 sum += num;
         double average=(double)sum/n;
         System.out.println("Average of " + n + " Numbers = " + average);

Java Program to Find Average of N Numbers

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles