Java Program to print the sum of all the elements of the array - The Coding Shala

Home >> Java Programs >> Sum of Array elements

 In this post, we will write a Java program to print the sum of all the elements of the array.

Java Program to print the sum of all the elements of the array

Write a Java program to find the sum of all the elements of the given integer array.

Example 1:
Input: [1, 2, 3, 4, 5]
Output: 15
Explanation: Sum of all the elements is = 1 + 2 + 3 + 4 + 5 = 15

Approach 1

Using loop we can find the sum of array elements.

Java Program: 

// print sum of all the elements of the array java program

public class Main {
	
	public static int findSum(int[] nums) {
		int sum = 0;
		// Iterate using loop
		for(int i = 0; i < nums.length; i++) {
			sum = sum + nums[i];
		}
		return sum;
	}
	
	public static void main(String[] args) { 
		int[] arr = {1, 4, 7, 9, 10};
		int sum = findSum(arr);
		System.out.println("Sum of all the elements is: " + sum);
	}
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala