# 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 :
```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:
1. Create a static array of some fixed size, along with element declaration
2. Build a function with a single argument, in which we will pass array argument
3. Inside this function, all the elements of the array are accessed one-by-one, adding to return the sum
4. 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;

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;

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]);

printf("\n Sum of all array elements = %5d \n", sum);

return 0;
}

// Function to add array elements using pointer
{

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

*/```