Explore Java Hacks and Tutorials
Be Social. Be Updated.

Add All Elements In Array in Java


An example on adding all the elements in an array that user gives. A really simple logic involving 2 main steps.

Add all Elements in Array



import java.util.*;
class SumArray
{


public static void main(String args[])
{


// Create a Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);


// Take the no.of elements that user want to sum
int n=s.nextInt();


// Create an array of given size (n)
int[] a=new int[n];


// Initialize sum to 0
int sum=0;


// Loop till end of array
for(int i=0;i<a.length;i++)
{


// Read int from user and store it in each element
a[i]=s.nextInt();


// Sum every element that user gives and store it in sum
sum+=a[i];


}


System.out.println("The sum of all the elements is "+sum);


}


}


Output



5
1
2
3
4
5
The sum of all the elements is 15


Tips:

You can also use n instead of a.length

sum+=a[i] is equal to sum=sum+a[i]


Similarly you can apply this logic for other data types also. If you apply for a char, a string will be resulted if you apply for a string concatenation will be done and might appear as a sentence. For other numeric data types like long,float,double etc, you'll get the sum.

Analysis


n=5: No. of elements to be added are 5

sum=0: Initially the sum of all the elements is 0.

a[i]=s.nextInt(): Initially at first i=0, afterwards i increments.

a[0]=1

0=0+1 = 1 => sum=1

a[1]=2

1=1+2 = 3 => sum=3

a[2]=3

3=3+3 = 6 => sum=6

a[3]=4

6=6+4 = 10 => sum=10

a[4]=5

10=10+5 = 15 => sum=15

End of loop. Control comes out. The value in sum (15) will be printed.



Posted by at on

Tags: Arrays