C program to calculate the sum of natural numbers (Using Recursion)

by | Jan 20, 2023 | C, C Programs

Home » C » C Programs » C program to calculate the sum of natural numbers (Using Recursion)

Introduction

This program is used to calculate the sum of first n natural numbers, where n is any value up to the user’s wish to calculate the sum.

To understand this program, you all should know about

1. Recursion

2. User-defined Functions in C

Go through the article ‘Functions’ written in the C language series to get a better understanding. Also, gain some knowledge about Recursion and its uses.

Recursion is the process in which a function calls itself.

The positive numbers that start from 1 are known as Natural numbers.

The sum begins from 1 since natural numbers start from 1.

Program

#include<stdio.h>
int addition(int a) //Declaration of function
{ // definition of the function
if(a!=0)
{
return a+ addition(a-1);
}
else
{
return a;
}
}
int main()
{
int x;
printf("Enter a positive integer:\n");
scanf("%d",&x);
int sum=addition(x); //function call and the value is assigned to variable sum
printf("Sum of the natural numbers upto %d is %d",x,sum);
return 0;
}

 

Output

Explanation

Variable ‘x’ will store the value up to which the user wants to calculate the sum.

Now go to the declaration of the function named ‘addition’.

int addition(int a)

Variable ‘a’ is passed as an argument in the function.

Now understand the code written inside the definition of the addition function.

if(a!=0)

If the value of ‘a’ is other than 0, then the next statement will get executed.

return a+ addition(a-1); it means there is an addition of ‘a’ with the value obtained when ‘a-1’ is passed in the same function. This is recursion i.e. addition function calling itself.

The final value is assigned to the ‘sum’ variable in the main function.

The value given by the user is 100 which is the value of ‘x’ and passed in the addition function.

Now the function statement will be executed as int addition(100)

Since ‘a’ is not 0 thus return a+ addition(a-1); will return

100+addition(99)

In this way, recursion takes place and proceed until we get

1+addition(0).

 

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author