JAVA program to find sum of elements in an array

JAVA program to find sum of elements in an array

This JAVA program is to find sum of elements in an array.

For example, if my array contains 4 elements let us say these elements are {9, 12 , 13, 6} then their sum would be 40.

Logic

We use a for loop and keep adding elements till we reach n.

Dry Run of the Program

Let us take number of elements n. Let us take n=3

Then run a for loop for n(3) elements and store it inside array ‘a’.

Let us take an input array ‘a’. Let us take elements for array a={7,12,21}

1st iteration for(i=0;i<n;i++) i.e. for(i=0;i<3;i++)

sum=sum+a[i];  i.e. sum=0+a[0]; i.e. sum=0+7; i.e. sum=7

2nd iteration for(i=0;i<n;i++) i.e. for(i=1;i<3;i++)

sum=sum+a[i];  i.e. sum=7+a[1]; i.e. sum=7+12; i.e. sum=19

1st iteration for(i=0;i<n;i++) i.e. for(i=2;i<3;i++)

sum=sum+a[i];  i.e. sum=19+a[2]; i.e. sum=19+21; i.e. sum=40

After this you come out of the for loop as i is not less than 3( i(3) < 3)

Hence sum=40.

Program

import java.util.*;

class arr1
{  
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		int i,n,sum=0;
		System.out.println("Enter the number of elements:") ;
 		n = sc.nextInt();
		int[] a = new int[n];
 
    		System.out.println("Enter the elements") ;
    		for(i=0;i<n;i++)
    		{
        		a[i] = sc.nextInt();
    		}
    		for(i=0;i<n;i++)
    		{
        		sum=sum+a[i];
    		}
    	
		System.out.println("Sum of "+n+" elements in an array = "+sum);
	}
}

Output

Share Me!