Q16.Write a code to find sum of array elements
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[]={ 2, 5, 3, 6, 4 }
output : 20
So as we can see that the sum of elements in arr[] = { 2, 5, 3, 6, 4 } is 20 so the output is 20.
Algorithm for Array Sum
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
Code for Array Sum
#include <stdio.h>
int main() {
int array[10] = { 2, 5, 3, 6, 4 };
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]={ 2, 5, 3, 6, 4 }, sum=0;
for(i = 0; i < 5; ++i)
{
sum += num[i];
}
cout << “Sum of array is = ” << sum;
return 0;
}
class LFC
{
static int arr[] = { 2, 5, 3, 6, 4 };
// 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 = [2, 5, 3, 6, 4]
# start parameter is not provided
numbers_sum = sum(numbers)
print (“Sum of array is = “,numbers_sum)
$a=array(2, 5, 3, 6, 4);
echo “Sum of array is “;
echo array_sum($a);
Output
Sum of array is = 20
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number