Thursday, 16 March 2017

C Program to calculate Sum of Array

C Program to calculate the sum of array is given below. Approach is simple we will traverse the array and add the respective element.

For Example: arr[]={2, 5, 8, 11, 14}, sum=0
                     
Pass 1, i=0:      sum = sum + arr[0] = 0 + 2 = 2
Pass 2, i=1:      sum = sum + arr[1] = 2 + 5 = 7
Pass 3, i=2:      sum = sum + arr[2] = 7 + 8 = 15
Pass 4, i=3:      sum = sum + arr[3] = 15 + 11 = 26
Pass 5, i=4:      sum = sum + arr[4] = 26 + 14 = 40

Program:


#include <stdio.h>
int main()
{
   int n,arr[100],i,sum=0;

   printf("\nEnter the total number of elements: ");
   scanf("%d",&n);

   printf("\nEnter the elements of the array: \n");
   for(i=0;i<n;i++)
   {
          scanf("%d",&arr[i]);
   }

   for(i=0;i<n;i++)
   {
          sum=sum+arr[i];
   }


   printf("\nSum of array is: %d",sum);
   printf("\n");

   return 0;
}


OUTPUT:


EmoticonEmoticon