Recursive Sum Example

Posted: November 1, 2010 in Uncategorized

Here is a recursive function that takes a number inputted by the user and find the sum of all numbers from 1 to that number:

#include <iostream>
using namespace std;

int recursion(int num);

int main(){

int num = 0;
int sumNum;

cout << “Enter any integer greater than 0: ” << endl;
cin >> num;

sumNum = recursion(num);
cout << “The sum is: ” << sumNum << endl;
cin.ignore();
cin.get();

return 0;
}

int recursion(int num)
{
int sum = 0;
if(num == 1){
return 1;
}
else{
sum = recursion(num-1) + num;
return sum;
}

}

Happy coding!

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s