C Program to Find Sum of Array Elements

Program description:- Write a C program to find the sum of the array elements. Take an array from the end-user and then add its elements and display its result value.

Let, we have an array of five integers a[5] then the sum of array elements given as a[0] + a[1] + a[2] + a[3] + a[4] 
The index of the array always starts from 0, not 1. so the first element will be a[0].

#include<stdio.h>
int main()
{
   // Array of 5 floating elements
   float arr[5], sum=0.0; 
   int i;

   printf("Enter array elements:\n");

   //  take 5 number
   for(i=0;i<5;i++)
   {
     scanf("%f",&arr[i]);
   }

   // add that 5 number
   for(i=0;i<5;i++)
   {
     sum += arr[i]; //sum=sum+arr[i]
   }

   printf("Sum of Array elements are: %f", sum);

   return 0;
}

In this C program, first we declare an array of floating point value of size 5, you can ask size of array from the end-user and then declare then variable. Then take a sum variable and initialize it with 0. Now take array elements as input and then add it to the sum. Finally display the sum value.

We used two for loop first for loop used for reading the array element and second for loop used for adding array elements. Instead of two for loops, only one for loop can be used. Both reading and adding of elements will be done inside one for loop.

#include<stdio.h>
int main()
{
   // Array of 5 floating elements
   float arr[5], sum=0.0; 
   int i;

   printf("Enter array elements:\n");

   // take number and add it with sum
   for(i=0;i<5;i++)
   {
     scanf("%f",&arr[i]);
     sum+=arr[i]; // sum=sum+arr[i]
   }

   printf("Sum of Array elements are: %f",sum);

   return 0;
 }

Output:-

Enter array elements:
2.5
3.2
5
9.8
5.7
Sum of Array elements are: 26.200001

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Similar C programming examples on Arrays

Leave a Comment

Your email address will not be published. Required fields are marked *