C Program to find Sum of Array Elements
Problem: If an array of integers is given find the sum of its elements. Calculate sum of array elements using pointer as argument.
Examples :
Solution:
Examples :
array[] = {10, 20, 30, 40, 50}
Sum of Array: 150
10 + 20 + 30 + 40 + 50 = 150
array[] = {1, 2, 3, 4, 5}
Sum of Array: 15
1 + 2 + 3 + 4 + 5 = 15
Solution:
- Create a static array of some fixed size, along with element declaration
- Build a function with a single argument, in which we will pass array argument
- Inside this function, all the elements of the array are accessed one-by-one, adding to return the sum
- Return sum to the called function and print it.
C program to find sum of array elements
/* Aim: C program to find the sum of all elements. */
#include<stdio.h>
int main()
{
int array[100];
int sum=0,size,i;
int addnum(int *ptr);
printf("\n Enter the size of array:- ");
scanf("%d",&size);
printf("\n Enter array elements:- ");
for(i=0;i<size;i++)
scanf("%d",&array[i]);
for(i = 0; i < 5; i++)
sum += array[i];
printf("\n Sum of all array elements = %5d \n", sum);
return 0;
}
/* Output of above code:-
Enter the size of array:- 5
Enter array elements:- 10 11 12 13 14
Sum of all array elements = 60
*/
C program to find sum of array elements using pointers and function
/* Aim: C program to find the sum of all elements of an array using pointer as argument to function */
#include<stdio.h>
int main()
{
static int array[100];
int sum,size,i;
int addnum(int *ptr);
printf("\n Enter the size of array:- ");
scanf("%d",&size);
printf("\n Enter array elements:- ");
for(i=0;i<size;i++)
scanf("%d",&array[i]);
sum = addnum(array);
printf("\n Sum of all array elements = %5d \n", sum);
return 0;
}
// Function to add array elements using pointer
int addnum(int *ptr)
{
int i, sum = 0;
for(i = 0; i < 5; i++)
sum += *(ptr + i);
return(sum);
}
/* Output of above code:-
Enter the size of array:- 5
Enter array elements:- 10 11 12 13 14
Sum of all array elements = 60
*/
C program to calculate sum of array elements using dynamic memory allocation
/* Aim: C program to read N integers and store them in an array A. Find the sum of all these elements using pointer. */
#include<stdio.h>
#include<malloc.h>
int main()
{
int i, n, sum = 0;
int *a;
printf("\n Enter the size of array:- ");
scanf(" %d", &n);
a = (int *) malloc(n * sizeof(int));
printf("\n Enter Elements:- ");
for (i = 0; i < n; i++)
scanf(" %d", a + i);
for (i = 0; i < n; i++)
sum = sum + *(a + i);
printf("\n Sum of all elements in array = %d \n", sum);
return 0;
}
/* Output of above code:-
Enter the size of array:- 5
Enter array elements:-
10
20
30
40
50
Sum of all elements in array = 150
*/