C Program to find the Sum of First n Natural numbers

In this tutorial, i am going to show you how to find sum of first n natural in c program with the help of for loop, while loop, function, and recursion.

Using the following mathematical formula to find the sum of n natural numbers in c program; as follows:

Sum of n natural number = n * (n + 1) / 2  

All C Programs find the Sum of First n Natural numbers

  • C Program to find the Sum of First n Natural numbers using For Loop
  • C Program to find the Sum of First n Natural numbers using While Loop
  • C Program to find the Sum of First n Natural numbers using Function
  • C Program to find the Sum of First n Natural numbers using Recursion

C Program to find the Sum of First n Natural numbers using For Loop

#include<stdio.h>
int main()
{
  int Number, i, Sum = 0;
  
  printf("\nPlease Enter any Integer Value\n");
  scanf("%d", &Number);
  
  for(i = 1; i <= Number; i++)
  {
     Sum = Sum + i;
  }
  
  printf("Sum of Natural Numbers = %d", Sum);
  return 0;
}

The result of the above c program; as follows:

Please Enter any Integer Value :- 50
Sum of Natural Numbers = 1275

C Program to find the Sum of First n Natural numbers using While Loop

#include<stdio.h>
int main()
{
  int Number, i = 1, Sum = 0;
  
  printf("\nPlease Enter any Integer Value :- ");
  scanf("%d", &Number);
  
  while(i <= Number)
  {
     Sum = Sum + i;
     i++;
  }
  
  printf("Sum of Natural Numbers = %d", Sum);
  return 0;
}

The result of the above c program; as follows:

Please Enter any Integer Value :- 100
Sum of Natural Numbers = 5050

C Program to find the Sum of First n Natural numbers using Function

/*
* C program to find sum of n numbers using function
*/
#include<stdio.h>
/*Write sum function that recieves the number
* as an argument up to which you want to sum.
* Return the total sum
*/
int sum(int num){
	int i;
	int sum =0;
	//Loop through from 1 to num e.g.
	//if number is 3 so index will start from
	// 1 to 3 and sum will be as = 1+2+3 = 6
	for(i=1; i<=num; ++i){
		sum += i; // Also, this can be written as sum = sum +i;
	}
	return sum;
}
/*
* Test sum of n numbers
*/
int main(){
	int num =0;
	int result =0;
	printf("Enter number ");
	//Read the number up to which you want sum
	scanf("%d", &num);
	//call sum function that will return sum
	result = sum(num);
	printf("sum : %d ",result);
	return 0;
}

The result of the above c program; as follows:

Enter number 50
sum : 1275 

C Program to find the Sum of First n Natural numbers using Recursion

#include <stdio.h>
int addNumbers(int n);
int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d", &num);
    printf("Sum = %d", addNumbers(num));
    return 0;
}
int addNumbers(int n) {
    if (n != 0)
        return n + addNumbers(n - 1);
    else
        return n;
}

The result of the above c program; as follows:

Enter a positive integer: 500
Sum = 125250

More C Programming Tutorials

Leave a Comment