array sum in java
👉 source code for array sum in java programming language
package CodeYourslf.arrayProblem; import java.util.Scanner; public class arraySum { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array: "); int size = sc.nextInt(); int[] arr = new int[size]; System.out.println("Enter the elements of array: "); for(int i = 0; i < size; i++){ arr[i] = sc.nextInt(); } int len1 = arr.length; int sum = 0; for(int i = 0;i<=len1-1; i++){ sum = sum + arr[i]; } System.out.println("The sum of the array elements is: "+sum); } }
output
How to find sum of array elements in java
- I will explain the logic part of this question by an example i.e.
let's declare an integer array of size 5.
int[] arr = {3,7,2,4,8};
- Finding the sum of array elements mean to find the sum of 2,7,...,8 i.e 3+7+2+4+8 = 2
How to do that
- First of all we have to know how to find the element present in the respective position, I mean
arr[0] will give the element present in the 0 index, here arr[0] = 2;
like that arr[1] will give element present in first index.
- Now arr[0] + arr[1] + + arr[2] + arr[3] + arr[4] = 3 + 7 + 2 + 4 + 8, which is 24.
- Here only 5 elements are so you can able to write arr[0] like this upto last, but there are 1000 elements in the array, then we have to write 1000 extra lines of code to add all the elements. Which is not possible.
- So in this case you should use for loop to find the sum of all elements.
see how ??
int sum = 0;
for(int i = 0; i < arr.length; i++){
sum = sum +arr[i];
}
- Here for the first time, the sum will be 0 and when it enter to the loop, the sum will be sum + arr[0] as i = 0.
So here sum become sum + arr[0] = 0 + 3 = 3.
Now the i will be incremented and become 1, Now sum will be sum + arr[i]
So now here sum become sum + arr[1] = 3 + 7 = 10.
👉 Like wise upto the last, it will do the same, and finally the sum become 24 here.