C Program to calculate sum of array elements

Simple C program to calculate sum of array elements
To calculate sum of array elements, first we declare sum and initialize it to 0. Then add array elements one by one.
 
/* C program to calculate sum of array elements */
#include<stdio.h>
int main()
{
 int n;
 printf("Enter size of array: ");
 scanf("%d",&n);
 int arr[n],i,sum=0;
 printf("Enter array elements: \n");
 for(i=0;i<n;i++)
 {
  printf("Enter %d element: ",i+1);
  scanf("%d",&arr[i]);
 }
 for(i=0;i<n;i++)
 {
  sum=sum+arr[i];
 }
 printf("Sum of array elements: %d\n",sum);
 return 0;
}
/* End of program */
 
Another C program to add array elements
 
/* C program to calculate sum of array elements */
#include<stdio.h>
int main()
{
 int n;
 printf("Enter size of array: ");
 scanf("%d",&n);
 int arr[n],i,sum=0;
 printf("Enter array elements: \n");
 for(i=0;i<n;i++)
 {
  printf("Enter %d element: ",i+1);
  scanf("%d",&arr[i]);
  sum=sum+arr[i];
 }
 printf("Sum of array elements: %d\n",sum);
 return 0;
}
/* End of program */
 
Another C program to add array elements using recursion
 
/* C program to calculate sum of array elements */
#include<stdio.h>
int SumOfArrayElements(int arr[],int n)
{
 if(n==0)
 return arr[0];
 return arr[n]+SumOfArrayElements(arr,n-1);
}
int main()
{
 int n;
 printf("Enter size of array: ");
 scanf("%d",&n);
 int arr[n],i,sum=0;
 printf("Enter array elements: \n");
 for(i=0;i<n;i++)
 {
  printf("Enter %d element: ",i+1);
  scanf("%d",&arr[i]);
 }
 sum=SumOfArrayElements(arr,n-1);
 printf("Sum of array elements: %d\n",sum);
 return 0;
}
/* End of program */
 
OR
 
/* C program to calculate sum of array elements */
#include<stdio.h>
int SumOfArrayElements(int arr[],int i,int n)
{
 if(i==n)
 return arr[i];
 return arr[i]+SumOfArrayElements(arr,i+1,n);
}
int main()
{
 int n;
 printf("Enter size of array: ");
 scanf("%d",&n);
 int arr[n],i,sum=0;
 printf("Enter array elements: \n");
 for(i=0;i<n;i++)
 {
  printf("Enter %d element: ",i+1);
  scanf("%d",&arr[i]);
 }
 sum=SumOfArrayElements(arr,0,n-1);
 printf("Sum of array elements: %d\n",sum);
 return 0;
}
/* End of program */


Popular posts from this blog