C++ Program to Calculate Sum of Natural Numbers (Using recursion)


This program is used to calculate the sum of the 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.



using namespace std;

int addition(int a) //Declaration of function

{ // definition of the function



return a+ addition(a-1); // recursion




return a;



int main()


int x;

cout<<"Enter a positive integer: ";


int sum=addition(x); //function call and the value is assigned to variable sum

cout<<"Sum of the natural numbers upto "<<x<<" is: "<<sum;

return 0;





int num;

‘num’ is the variable declared to store the value up to where the user wishes to calculate the sum.

cout<<“Enter a positive integer: “;


Using cout and cin statements we take input from the user.

int sum=0;

A new variable is declared and initialized with a 0 value to store the sum of natural numbers.

int i=1;

The iterator ‘i’ is initialized with 0 value.


The while loop starts here with a condition and it will iterate until the condition gives a false result.


In each iteration, the value of ‘i’ is added to ‘sum’.


After that, the value of ‘i’ is incremented by 1.

When the condition in the while loop becomes false, the loop gets terminated and the final value of the ‘sum’ is printed.



  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.


Leave a Reply

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.