Java Program to print the sum of all the elements of the array - The Coding Shala
Home >> Java Programs >> Sum of Array elements
Other Posts You May Like
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); } }
- Java Program to generate random numbers
- Java Program to swap two numbers
- Java Program to reverse a string
- Java Program to Add two numbers
- Java Program to Swap two numbers using XOR
Comments
Post a Comment