sum of natural numbers program
C programming Tutorials

Sum of Natural Numbers Program using Recursion

Sum of Natural Numbers Program using Recursion

C Program to find Sum of Natural Numbers using Recursion is discussed here in this tutorial.

Algorithm

Step 1 – First we declared a function sum( ) to calculate the sum of N natural numbers which accept a parameter K  here K represent to the number up to which we have to find the sum.

Step 2 – Declare variable num to accept the input from user.

Step 3 – Declare variable result to store the vale of sum return by the sum() function.

Step 4 – Define the body of function sum( ) in which return statement (k +sum(k-1)) is a recursive call to sum().

 Step 5 – When sum() function is called inside main() function then program control will transfer to body of sum() and sum() function will be execute and sum to number from 1 to k will be performed and return by function which will be stored in result variable.

Step 6 – Print the value of result variable to print the sum.

C Program 

#include <stdio.h>

int sum(int k);

int main()

{

int num,result;

printf(“Enter a positive integer up to which you want sum “);

scanf(“%d”, &num);

result=sum(num);

printf(“Sum = %d”,result);

return 0;

}

int sum(int k)

{

if(k>0)
{
return (k+ sum(k- 1));
}

else

return 0;

}

Output

sum of natural numbers program

When we execute the above program and will enter the 10 as value of k then sum up from 1 to 10 it means 55 will be printed.

Leave a Reply

Your email address will not be published. Required fields are marked *