Java Program to find sum of n numbers using array

In the following question, we are supposed to enter integer inputs in an array. The array will be a dynamic array of size N. After entering into the array, we’ll have to calculate and print the Summation of all the elements in the array.

The standard algorithm will be:

  1. Prompt the user to enter the size of the array (number of rows and columns).
  2. Create a matrix of the input size using a nested loop.
  3. Within the nested loop, prompt the user to enter an integer value for each element in the matrix.
  4. Declare a variable to store the summation of all the elements in the original matrix. Initialize it to 0.
  5. Using another nested loop, iterate through the matrix and perform the cumulative summation of all the elements.
  6. After the loop terminates, print the result.

Source Code:

/* Program to Add N numbers user enters in Array and displaying the sum*/
import java.util.*;

class ArrSumOfNum
{
    public static void main()
    {
        Scanner inp = new Scanner(System.in);
        System.out.print("\n Enter Number of Numbers to be Calculated: ");
        int n = inp.nextInt();
        int i, sum = 0;
        int arr[] = new int[n]; //Creating N-size Array

        for (i = 0; i < n; i++) //Entering N numbers in array
        {
            System.out.print("\n Enter: ");
            arr[i] = inp.nextInt();
        }

        System.out.println();
        for (i = 0; i < n; i++)
        {
            System.out.print(arr[i]);
            sum = sum + arr[i]; //Cumulative Sum

            if (i < (n - 1))
                System.out.print(" + ");
            else
                System.out.print(" = ");
        }

        System.out.print(sum);
    }
}

Output:

Enter Number of Numbers to be Calculated: 5

Enter: 63

Enter: 64

Enter: 54

Enter: 29

Enter: 38

63 + 64 + 54 + 29 + 38 = 248
Java Program to find sum of n numbers using array