Need a project done?

C++ Programming Developer

Search This Blog

Recursive function to calculate Sum of all numbers from 1 to n in C++

Write a recursive function in C++ that computes the sum of all numbers from 1 to n, where n is given as parameters.
Solution:

#include <iostream>
using namespace std;
int sum(int);
int main()
{
 int x; cout << "Write a number, I'll tell u sum of all numbers from 1 to your number: "; cin>>x;

 cout << "\nSum of all numbers from 1 to " << x << " is: " << sum(x) << endl;
}
int sum(int x)
{
 if (x==1)
  return 1;
 else
  return x+sum(x-1);
}

1 comment:

"Don't let anyone ever make you feel like you don't deserve what you want."