Q. Write a program to find sum of elements in a given array.
Array :- An array is a collection of data items, all of which are of the same type, using a common name.
For Example :-
input : arr[]={ 8, 9, 1, 2, 4 }
output : 24
So as we can see that the sum of elements in arr[] = {8, 9, 1, 2, 4 } is 24 so the output is 24.
Array Sum Algorithm
START Step 1 : Take an array Arr and define its values Step 2 : Loop for each value of Arr Step 3 : Add each element to 'sum' variable Step 4 : After the loop finishes, display 'sum' STOP
Array Sum Program
#include <stdio.h> int main() { int array[10] = {9, 8, -15, 30, 0}; int sum, loop; sum = 0; for(loop = 9; loop >= 0; loop--) { sum = sum + array[loop]; } printf("Sum of array is = %d", sum); return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int i, num[5]={9, 8, -15, 30, 0}, sum=0; for(i = 0; i < 5; ++i) { sum += num[i]; } cout << "Sum of array is = " << sum; return 0; }
class LFC { static int arr[] = {9, 8, -15, 30, 0}; // method for sum of elements in an array static int sum() { int sum = 0; // initialize sum int i; // Iterate through all elements and add them to sum for (i = 0; i < arr.length; i++) sum += arr[i]; return sum; } // Driver method public static void main(String[] args) { System.out.println("Sum of array is = " + sum()); } }
numbers = [9, 8, -15, 30, 0] # start parameter is not provided numbers_sum = sum(numbers) print ("Sum of array is = ",numbers_sum)
using System; using System.Collections.Generic; using System.Linq; class LFC { static void Main() { // // Declare two collections of int elements. // int[] array1 = { 9, 8, -15, 30, 0 }; int sum1 = array1.Sum(); Console.WriteLine("Sum of array is = "+sum1); } }
$a=array(9, 8, -15, 30, 0); echo "Sum of array is "; echo array_sum($a);
#include <stdio.h> int main() { int array[10] = {9, 8, -15, 30, 0}; int sum, loop; sum = 0; for(loop = 9; loop >= 0; loop--) { sum = sum + array[loop]; } printf("Sum of array is = %d", sum); return 0; }
Output
Sum of array is = 32
Recommended Programs
Prime Number ProgramLeap Year Program