Sum of n numbers in C

In this article we will print sum of n numbers in C. A user will give the number that how many numbers he want to add and then we will print the sum of given n numbers using C programming language. We can do it by a number of methods and here we will discuss that using array, function etc. See, some C programs to print sum of n numbers bellow.

Printing sum of n numbers using loop in C

// Printing sum of n numbers using loop in C
#include <stdio.h>
int main(){
  int num, result = 0, j, allNum;

  printf("Enter how many integers you want to add : ");
  scanf("%d", &num);

  printf("\nEnter %d integers to add them : \n", num);

  for (j = 1; j <= num; j++){     // for loop to add all numbers
    scanf("%d", &allNum);
    result = result + allNum;
  }

  printf("Sum is = %d\n", result);

  return 0;
}

Output of this sum of n numbers program

sum of n numbers using c programming

Determining sum of n numbers using function in C

// Printing sum of n numbers using function in C
#include <stdio.h>

long printSum(int a[], int num) {    // function to add all number
  static long sum = 0;

  if (num == 0)
    return sum;

  sum = sum + a[num-1];

  return printSum(a, --num);
}

int main(){
  int num, i, array[100];
  long result;

  printf("Enter how many integers you want to add : ");
  scanf("%d", &num);

  for (i = 0; i < num; i++){
    printf("\nEnter number %d integer : ", i + 1);
    scanf("%d", &array[i]);
    }
  result = printSum(array, num);

  printf("\nSum is = %ld\n", result);

  return 0;
}

See the output of this program

Sum of n numbers using array in C

// Printing sum of n numbers using array in C
#include <stdio.h>
int main(){
   int num, sum = 0, i, myArray[100];
    printf("Enter how many number you want to add : ");
   scanf("%d", &num);

   for (i = 0; i < num; i++){
      printf("\nEnter number %d here : ", i+1);
      scanf("%d", &myArray[i]);
      sum = sum + myArray[i];
   }

   printf("\nSum is = %d\n", sum);

   return 0;
}

Output

add n numbers using c programming language

Previous pagePrime numbers in C

Next pageProgram to find factorial