Home » Program to print the sum of all the elements of an array

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

by Online Tutorials Library

Q. Program to print the sum of all the elements of an array.

Explanation

In this program, we need to calculate the sum of all the elements of an array. This can be solved by looping through the array and add the value of the element in each iteration to variable sum.

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

Sum of all elements of an array is 1 + 2 + 3 + 4 + 5 = 15.

Algorithm

  1. Declare and initialize an array.
  2. The variable sum will be used to calculate the sum of the elements. Initialize it to 0.
  3. Loop through the array and add each element of array to variable sum as sum = sum + arr[i].

Solution

Python

Output:

Sum of all the elements of an array: 15  

C

Output:

Sum of all the elements of an array: 15  

JAVA

Output:

Sum of all the elements of an array: 15  

C#

Output:

Sum of all the elements of an array: 15  

PHP

Output:

Sum of all the elements of an array: 15  

Next Topic#

You may also like