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.in);
System.out.print("Enter How Many Numbers : ");//input
n =input.nextInt(); //read total numbers
System.out.print("Enter the Numbers :");
num=input.nextInt(); //input number
sum += num;
System.out.println("Average of " + n + " Numbers = " + average);