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. Enter the size of the array.
2. Create the matrix of the input size.
3. Using a loop construct, enter integer inputs in the matrix.
4. Declare a variable that will store the summation of all the elements of the original matrix.
5. Initialize it with 0.
6. Using a loop construct, perform the cumulative summation of the array elements.
7. After the loop terminates, print the result accordingly.

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

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019