Sum of first N natural numbers in C

In this guide we will see some C program to find the sum of natural numbers. We know that natural numbers are all the positive numbers starting from 1 to any positive number.

Natural numbers :  1,  2,  3,  4,  5,  6,  7,  8,  9,  10,  11 ……..

To determine the sum of first N natural numbers in C, we can write the program in many ways. For example, we can make the program using any loop, mathematical formulae, function or recursion. Here we will see all the program to find the sum of first N natural numbers.

Sum of natural numbers using mathematical formulae

The mathematical formulae for determining the sum of first N natural numbers is given bellow;

Sum = n * (n + 1) / 2 

We can use this formulae to calculate the sum of first N natural numbers. Let’s see the program here.

// Sum of N natural numbers using mathematical formulae

#include <stdio.h>
int main(){
  int N, sum;
  printf("Enter the value of N here : ");
  scanf("%d", &N);

  sum = (N * (N + 1)) / 2;
  printf("\nSum of first %d natural numbers is = %d\n", N, sum);

  return 0;
}

Output of this sum of natural number program :

sum-of-n-natural-numbers-in-c-sum-of-natural-numbers

Sum of natural numbers using loop in C

We can also make the sum of  natural numbers program using any loop although we will use for loop to write the program. You can use any loop to determine the sum. Let’s go ahead with code.

// Sum of natural numbers using for loop

#include <stdio.h>
int main(){
  int N, c, sum = 0;
  printf("Enter how many numbers you want to add : ");
  scanf("%d", &N);
  for(c = 0; c <= N; c++){
    sum = sum + c;
  }
  printf("\nSum of first %d natural numbers is = %d\n", N, sum);
  return 0;
}

Output of program :

Enter how many numbers you want to add : 30

Sum of first 30 natural numbers is = 465

Sum of N natural numbers using array

In this C program we will use array to determine the sum.

// Sum of natural numbers using array in C

#include <stdio.h>
int main(){
  int N, c, sum = 0;

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

  int arr[N];

  for(c = 0; c < N; c++){
    arr[c] = c + 1;
  }

  for(c = 0; c < N; c++){
    sum += arr[c];
  }

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

You will see the following output when you compile and run the program.

Enter how many number you want to add : 300

Sum is = 45150

Sum of natural numbers using function in C

// Sum of natural numbers using function in C

#include <stdio.h>
#include <conio.h>

int sum_of_num(int number);

int main(){
  int n, result;

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

  result = sum_of_num(n);

  printf("\nSum is = %d\n", result);
  return 0;
}

int sum_of_num(int number){
  int k, sum = 0;

  for (k = 0; k <= number; k++){
    sum += k;
  }
  return sum;
}

Output :

Enter how many number you want to add : 100

Sum is = 5050

Previous pagePerfect number program

Next pageBinary to decimal by C