C Program to Find Sum of Natural Numbers Using Recursion
In mathematics, natural numbers (1, 2, 3, 4, ...) are used for counting and ordering. Some definitions of natural numbers include 0 as the first number, but that doesn't really matter for finding the sum of natural numbers.
This C program finds the sum of first n natural numbers using a recursive function.
C Source Code: Sum of First n Natural Numbers Using Recursion
#include<stdio.h>
#include<conio.h>
/* function prototype */
int sum(int n);
int main()
{
int term, result;
clrscr();
printf("Enter number of terms (positive integer): ");
scanf("%d", &term);
/* function call */
result = sum(term);
printf("Sum of first %d natural numbers is %d", term, result);
getch();
return 0;
}
int sum(int n)
{
int s=0;
if(n<=0)
{
return 0;
}
return n + sum(n-1);
}
Output
The output of the above program is:
Enter number of terms (positive integer): 9 Sum of first 9 natural numbers is 45