Java Program to find Average of N Numbers

Using for loop

In the following example, we will find the average of numbers between 1 and 10 using for loop.

Example

Java Compiler
public class myClass { public static void main(String[] args) { int start = 1; int end = 10; int total = 0; int count = (end - start) + 1; float average = 0; System.out.format("Average of numbers between %d and %d:\n\n", start, end); for(start=start; start<=end; start++) total += start; System.out.println("Total = " +total); System.out.println("Count = " +count); average = (float) total / count; System.out.println("Average is " +average); } }

Using while loop

In the following example, we will find the average of numbers between 1 and 10 using while loop.

Example

Java Compiler
import java.lang.Math; public class myClass { public static void main(String[] args) { int start = 1; int end = 10; int total = 0; int count = (end - start) + 1; float average = 0; System.out.format("Average of numbers between %d and %d:\n\n", start, end); while(start <= end) { total += start; start++; } System.out.println("Total = " +total); System.out.println("Count = " +count); average = (float) total / count; System.out.println("Average is " +average); } }

Using do while loop

In the following example, we will find the average of numbers between 1 and 10 using do while loop.

Example

Java Compiler
import java.lang.Math; public class myClass { public static void main(String[] args) { int start = 1; int end = 10; int total = 0; int count = (end - start) + 1; float average = 0; System.out.format("Average of numbers between %d and %d:\n\n", start, end); do { total += start; start++; }while(start <= end); System.out.println("Total = " +total); System.out.println("Count = " +count); average = (float) total / count; System.out.println("Average is " +average); } }

Find Average of N Numbers for any Given Range

In the following example, we will find the average of N numbers between the user given range.

Example

Java Compiler
import java.util.Scanner; public class myClass { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter a (int) starting number: "); int start = reader.nextInt(); System.out.print("Enter an (int) ending number: "); int end = reader.nextInt(); int total = 0; int count = (end - start) + 1; float average = 0; System.out.format("Average of numbers between %d and %d:\n\n", start, end); for(start=start; start<=end; start++) total += start; System.out.println("Total = " +total); System.out.println("Count = " +count); average = (float) total / count; System.out.println("Average is " +average); } }

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author