# C Program to Find Sum of All Elements in an Array

Fundamentally, an array is a data structure containing a collection of values or variables. The simplest type of array is a linear array or one-dimensional array. An array can be defined in C with the following syntax:

int Arr[5] = {10, 20, 30, 40, 50};
/* here 10,20,30,40,50 are the elements at indices 0,1,2,3,4 respectively */

In this example, array Arr is a collection of 5 integers. Each integer can be identified and accessed by its index. The indices of the array start with 0. So, the first element of the array will have index 0, the next will have index 1 and so on.

Sum of an array is defined as the sum of all elements present in the array. For example, if the array is [10, 20, 30, 40, 50], the sum of this array is 10+20+30+40+50 = 150.

Problem Description

Write a C program that reads an array of N elements, calculates the sum of those N elements, and displays the result to the standard output or the screen.

Problem Solution

The sequence of steps for the solution will be as follows:
1. Take n, a variable that stores the number of elements of the array.
2. Create an array of size n.
3. Iterate via for loop or pointers to take array elements as input, and print them.
4. Iterate via for loop or pointers to access each element of array to get the sum of all the elements.
5. Print the sum of an array on the screen.

Let’s take a look at the following methods to find the sum of an array in C.

Method 1: (Using Loops and Variables)

In this approach, we find the sum of the array using a for loop and in each iteration we add the array element to the sum. After the loop is executed, we print the sum.

Examples:

Let size = “4” and the array is [1,2,3,4]
So, sum = 1 + 2 + 3 + 4 = 10

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Let size = “5” and the array is [1, 3, 2, 5, 4]
So, sum = 1 + 3 + 2 + 5 + 4 = 15

Program/Source Code

Here is the source code of the C program to find the sum of the array using a for loop. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

1. `/*`
2. ` * C Program to Find Sum of Array Elements using Loops and Variables`
3. ` */`
4. ` `
5. `#include <stdio.h>`
6. ` `
7. `int main()`
8. `{`
9. `    int size;`
10. `    printf("Enter size of the array: ");`
11. `    scanf("%d",&size);`
12. ` `
13. `    //Declaring array`
14. `    int arr[size];`
15. `    printf("Enter array elements\n");`
16. ` `
17. `    // Input array elements`
18. `    for(int i=0;i<size;i++)`
19. `    scanf("%d",&arr[i]);`
20. `    int sum=0;`
21. ` `
22. `    // Loop to find sum `
23. `    for(int i=0;i<size;i++)`
24. `    sum+=arr[i];`
25. ` `
26. `    //Print sum`
27. `    printf("Sum of the array is: %d",sum);`
28. ` `
29. `    return 0;`
30. `}`
Program Explanation

1. Input the array size value and store it in the size variable.
2. Input the array elements and store it in arr[i].
3. Traverse the array using for loop and add array element to sum i.e. sum+=arr[i];
4. Print the sum of the array.

Time Complexity: O(n)
In the above program, a loop is executed to traverse the loop, so the time complexity is O(n).

Space Complexity: O(n)
Space is required to store the array elements, so the space complexity is O(n).

Run Time Testcases

Testcase 1: To find the sum of array elements, enter “4” as the size and the array elements 1, 2, 3, and 4 as input.

```Enter size of the array: 4
Enter array elements
1 2 3 4
Sum of the array is: 10```

Testcase 2: To find the sum of array elements, enter “5” as the size and the array elements 1, 3, 2, 5, and 4 as input.

```Enter size of the array: 5
Enter array elements
1 3 2 5 4
Sum of the array is: 15```

Method 2: (Using Pointers)

In this approach, we find the sum of the array using pointers. A pointer is a variable which points to the memory location of the array. In each iteration we dereference the pointer and add it to the sum.

Examples:

If size = “3”, array = [2,4,1]
Sum of array = 2 + 4 + 1 = 7

If size = “6”, array = [8,4,2,5,3,7]
Sum of array = 8 + 4 + 2 + 5 + 3 + 7 = 29

Program/Source Code

Here is the source code of the C program to find the sum of the array using pointers. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

1. `/*`
2. ` * C Program to Find Sum of Array Elements using Pointers`
3. ` */`
4. ` `
5. `#include <stdio.h>`
6. ` `
7. `int main()`
8. `{`
9. `    int size;`
10. `    printf("Enter size of the array: ");`
11. `    scanf("%d",&size);`
12. `    int arr[size];`
13. `    printf("Enter array elements\n");`
14. `    for(int i=0;i<size;i++)`
15. `    scanf("%d",&arr[i]);`
16. `    int sum=0;`
17. ` `
18. `    // pointer ptr points at the first element`
19. `    int *ptr=&arr[0];`
20. `    for(int i=0;i<size;i++)`
21. `    {`
22. `        sum+=*ptr;`
23. ` `
24. `        //Incrementing pointer to next element`
25. `        ptr++;`
26. `    }`
27. `    printf("Sum of the array is: %d",sum);`
28. ` `
29. `    return 0;`
30. `}`
Program Explanation

1. Input the array size value and store it in the size variable.
2. Input the array elements and store it in arr[i].
3. Initialize sum=0 and a pointer that points at the first element to the array.
4. In each iteration dereference the pointer and add it to sum and increment the pointer.
5. Print the sum of array.

Time Complexity: O(n)
In the above program, a loop is executed to traverse the loop, so the time complexity is O(n).

Space Complexity: O(n)
Space is required to store the array elements, so the space complexity is O(n).

Run Time Testcases

Testcase 1: To find the sum of array elements, enter “3” as the size and the array elements 2, 4, and 1 as input.

```Enter size of the array: 3
Enter array elements
2 4 1
Sum of the array is: 7```

Testcase 2: To find the sum of array elements, enter “6” as the size and the array elements 8, 4, 2, 5, 3, and 7 as input.

```Enter size of the array: 6
Enter array elements
8 4 2 5 3 7
Sum of the array is: 29```

Method 3: (Using Recursion)

The prototype of the recursive function is: int sum(int n,int arr,int i).

Following is the function definition:

```int  sum(int n,int arr[],int i)
{
if(i==n)
return 0;
else
return arr[i]  + sum(n,arr,i+1);
}```

Example:

Now let n=5 and arr = [1,2,3,4,5] So function calls would be as follows.

```sum(5,arr,0)=1+sum(5,arr,1)  —— ——— ——— ——— ——— ———   15
sum(5,arr,1)=2+sum(5,arr,2) ——— ——— ————— —— 14
sum(5,arr,2)=3+sum(5,arr,3)  ——— ——— —- 12
sum(5,arr,3)=4+sum(5,arr,4)  ——— 9
sum (5,arr,4)=5+sum(5,arr,5)  —  5
sum(5,arr,5)=0 // Base Case```
Program/Source Code

Here is the source code of the C program to find the sum of the array using recursion. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

1. `/*`
2. ` * C Program to Find Sum of Array Elements using Recursion`
3. ` */`
4. ` `
5. `#include <stdio.h>`
6. `int sum(int n,int arr[],int i)`
7. `{`
8. `   //Base Condition`
9. `   if(i==n)`
10. `   return 0;`
11. `   else`
12. `   return arr[i]  + sum(n,arr,i+1); // Recursive Calls`
13. `}`
14. ` `
15. `int main()`
16. `{`
17. `    int size;`
18. `    printf("Enter size of the array: ");`
19. `    scanf("%d",&size);`
20. `    int arr[size];`
21. `    printf("Enter array elements\n");`
22. `    for(int i=0;i<size;i++)`
23. `    scanf("%d",&arr[i]);`
24. `    printf("Sum of array is: %d",sum(size,arr,0));`
25. ` `
26. `    return 0;`
27. `}`
Program Explanation

1. Input the size of array and store it in the size variable.
2. Input the array elements and store it in arr[i].
3. Declare a function sum which takes 3 parameters, first is the size, second is array and third is the current index which we are processing right now and it recursively calls itself for the next index until the complete array is traversed.

• Base case: When i=n, return 0 i.e when full array is traversed.
• Other cases: return arr[i] + func(n,arr,i++) // i denoted the current index of the array.

4. Print the value of sum as returned by the function.

Time Complexity: O(n)
In the above program, as there will be n function calls, so the time complexity is O(n).

Space Complexity: O(n)
Space is required to store an array of elements, so the space complexity is O(n).

Run Time Testcases

Testcase 1: To find the sum of array elements, enter “5” as the size and the array elements 1, 2, 3, 4, and 5 as input.

```Enter size of the array: 5
Enter array elements
1 2 3 4 5
Sum of the array is: 15```

Testcase 2: To find the sum of array elements, enter “4” as the size and the array elements 9, 2, 8 and 1 as input.

```Enter size of the array: 4
Enter array elements
9 2 8 1
Sum of the array is: 20```

Method 4: (Using Function and Pointers)

The prototype of the recursive function is: int sum(int *ptr,int n).

In this approach, it takes two parameters, one is pointer to the array and other is the size of array.

Example:

If size = “4”, array = [1,2,3,4]
Sum of array = 1 + 2 + 3 + 4 = 10

Program/Source Code

Here is the source code of the C program to find the sum of the array using function and pointer. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

1. `/*`
2. ` * C Program to Find Sum of Array Elements using Function and Pointer`
3. ` */`
4. ` `
5. `#include <stdio.h>`
6. `int sum(int *ptr,int n)`
7. `{`
8. `   int s=0;`
9. `   for(int i=0;i<n;i++)`
10. `   {`
11. `       s += *ptr;`
12. ` `
13. `       //Incrementing pointer to next element`
14. `       ptr++;`
15. `   }`
16. `   return s;`
17. `}`
18. ` `
19. `int main()`
20. `{`
21. `    int size;`
22. `    printf("Enter size of the array: ");`
23. `    scanf("%d",&size);`
24. `    int arr[size];`
25. ` `
26. `    //Input array elements`
27. `    printf("Enter array elements\n");`
28. `    for(int i=0;i<size;i++)`
29. `    scanf("%d",&arr[i]);`
30. ` `
31. `    // Calling function by passing address of first element`
32. `    printf("Sum of array is: %d",sum(arr,size));`
33. ` `
34. `    return 0;`
35. `}`
Program Explanation

1. Input the size of array and store it in the size variable.
2. Input the array elements and store it in arr[i].
3. Declare a function sum to find the sum which takes a pointer to first element and size of array as parameter.
4. Intilaise s=0. Iterate over complete array with pointer and add it sum.
5. Print the value of sum as returned by the function.

Time Complexity: O(n)
In the above program, a loop is executed to traverse the loop, so the time complexity is O(n).

Space Complexity: O(n)
Space is required to store an array of elements, so the space complexity is O(n).

Run Time Testcases

Testcase 1: To find the sum of array elements, enter “4” as the size and the array elements 1, 2, 3, and 4 as input.

```Enter size of the array: 4
Enter array elements
1 2 3 4
Sum of the array is: 10```

Testcase 2: To find the sum of array elements, enter “3” as the size and the array elements 9, 4, and 8 as input.

```Enter size of the array: 3
Enter array elements
9 4 8
Sum of the array is: 21```

Method 5: Sum and Average of Array Elements using For Loop

In this approach, we will find the sum and average of an array using for loop.

The formula for the average of the array will be:
average=Σ(elements of the array)/number of elements in the array

Simply, we will add all the elements of the array and then divide it with the number of the elements to find the average.

Expected Input and Output

If we are entering 5 elements (N = 5), with array element values as 10, 20, 30, 40 and 50 then,
1. Sum of Elements of the array will be: 10 + 20 + 30 + 40 + 50 = 150
2. Average of Elements of the array will be: 150 / 5 = 30

Program/Source Code

Here is the source code of the C program to calculate the sum & average of an array. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

1. `/*`
2. ` * C program to read N integers into an array A and`
3. ` * a) Find the sum of all numbers`
4. ` * b) Find the average of all numbers`
5. ` * Display the results with suitable headings`
6. ` */`
7. ` `
8. `#include  <stdio.h>`
9. ` `
10. `int main()`
11. `{`
12. `    int i, num;`
13. `    float total = 0.0, average;`
14. `    printf ("Enter the value of N \n");`
15. `    scanf("%d", &num);`
16. `    int array[num];`
17. ` `
18. `    printf("Enter %d numbers (-ve, +ve and zero) \n", num);`
19. ` `
20. `    for (i = 0; i < num; i++)`
21. `    {`
22. `        scanf("%d", &array[i]);`
23. `    }`
24. ` `
25. `    printf("Input array elements \n");`
26. ` `
27. `    for (i = 0; i < num; i++)`
28. `    {`
29. `        printf("%+3d\n", array[i]);`
30. `    }`
31. ` `
32. `    /*  Summation starts */`
33. ` `
34. `    for (i = 0; i < num; i++)`
35. `    {`
36. `        total+=array[i];/* this means total=total+array[i]; */`
37. `    }`
38. ` `
39. `    average = total / num;`
40. ` `
41. `    printf("\n Sum of all numbers =  %.2f\n", total);`
42. ` `
43. `    printf("\n Average of all input numbers =  %.2f\n", average);`
44. ` `
45. `}`
Program Explanation

1. Take a number num as input, which will indicate the number of elements in the array.
2. Create an array of integer with user-defined size.
3. Iterating through for loops (from 0 to N)), take integers as input from the user and print them. These inputs are the elements of the array.
4. Now, start summation by iterating through all the elements and adding numbers to calculate the sum of the array.
5. To calculate the average, the overall sum is divided by the total number of elements in the array.
6. Print the sum and average values calculated.

Runtime Test Cases

Here is the runtime output of the C program where the user is reading an array of 5 integers with values 10,20,30,40 and 50 and the program is calculating and displaying the sum and average of the elements of the array.

```Enter the value of N
5
Enter 5 numbers (-ve, +ve and zero)
10
20
30
40
50

Input array elements
10
20
30
40
50

Sum of all numbers =  150

Average of all input numbers =  30```

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]