Monday, October 19, 2020

Java Program to Calculate Average Using Arrays

Oracle Java Certification, Oracle Java Learning, Oracle Java Tutorial and Material, Oracle Java Exam Prep

1. Overview

In this article, you’ll learn how to calculate the average of numbers using arrays. 

You should know the basic concepts of a java programming language such as Arrays and forEach loops.

We’ll see the two programs on this. The first one is to iterate the arrays using for each loop and find the average.

In the second approach, you will read array values from the user.

Let us jump into the example programs.

2. Example 1 to calculate the average using arrays

First, create an array with values and run. the for loop to find the sum of all the elements of the array.

Finally, divide the sum with the length of the array to get the average of numbers.

package com.oraclejavacertified.programs.arrays.average;

public class ArrayAverage {

    public static void main(String[] args) {

        // create an array

        int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

        // getting array length

        int length = array.length;

        // default sium value.

        int sum = 0;

        // sum of all values in array using for loop

        for (int i = 0; i < array.length; i++) {

            sum += array[i];

        }

        double average = sum / length;

        System.out.println("Average of array : "+average);

    }

}

Output:

Average of array : 6.0

3. Example 2 to find the average from user inputted numbers

Next, let us read the input array numbers from the user using the Scanner class.

import java.util.Scanner;

public class ArrayAverageUserInput {

    public static void main(String[] args) {

        // reading the array size.

        Scanner s = new Scanner(System.in);

        System.out.println("Enter array size: ");

        int size = s.nextInt();

        // create an array

        int[] array = new int[size];

        // reading values from user keyboard

        System.out.println("Enter array values :  ");

        for (int i = 0; i < size; i++) {

            int value = s.nextInt();

            array[i] = value;

        }

        // getting array length

        int length = array.length;

        // default sium value.

        int sum = 0;

        // sum of all values in array using for loop

        for (int i = 0; i < array.length; i++) {

            sum += array[i];

        }

        double average = sum / length;

        System.out.println("Average of array : " + average);

    }

}

Oracle Java Certification, Oracle Java Learning, Oracle Java Tutorial and Material, Oracle Java Exam Prep
Output:

Enter array size: 

5

Enter array values :  

12

23

34

45

56

Average of array : 34.0

Related Posts

0 comments:

Post a Comment