# Sum of n numbers in C

Sum of n numbers in C: This program adds n numbers which will be entered by a user. The user will enter a number indicating how many numbers to add and then the user will enter n numbers. To perform the arithmetic operation of addition of n numbers we can use an array or do it without using an array.

## C program to sum n numbers using a for loop

1. #include <stdio.h>
2.
3. int main()
4. {
5.   int n, sum = 0, c, value;
6.
7.   printf("How many numbers you want to add?\n");
8.   scanf("%d", &n);
9.
10.   printf("Enter %d integers\n", n);
11.
12.   for (c = 1; c <= n; c++)
13.   {
14.     scanf("%d", &value);
15.     sum = sum + value;
16.   }
17.
18.   printf("Sum of the integers = %d\n", sum);
19.
20.   return 0;
21. }

You can use long int or long long data type for the variable sum.

Output of program:

## C program to calculate sum of n numbers using an array

1. #include <stdio.h>
2.
3. int main()
4. {
5.    int n, sum = 0, c, array[100];
6.
7.    scanf("%d", &n);
8.
9.    for (c = 0; c < n; c++)
10.    {
11.       scanf("%d", &array[c]);
12.       sum = sum + array[c];
13.    }
14.
15.    printf("Sum = %d\n", sum);
16.
17.    return 0;
18. }

The advantage of using an array is that we have a record of the numbers entered by a user and can use them further in the program if required but storing numbers will require additional memory.

### C program for addition of n numbers using recursion

1. #include <stdio.h>
2.
3. long calculate_sum(int [], int);
4.
5. int main()
6. {
7.   int n, c, array[100];
8.   long result;
9.
10.   scanf("%d", &n);
11.
12.   for (c = 0; c < n; c++)
13.     scanf("%d", &array[c]);
14.
15.   result = calculate_sum(array, n);
16.
17.   printf("Sum = %ld\n", result);
18.
19.   return 0;
20. }
21.
22. long calculate_sum(int a[], int n) {
23.   static long sum = 0;
24.
25.   if (n == 0)
26.     return sum;
27.
28.   sum = sum + a[n-1];
29.
30.   return calculate_sum(a, --n);
31. }