/*QUESTION :
Write a recursive function that computes the sum of all numbers from 1 to n , where n is given as parameter by the user.
*/
//CODE:
#include <iostream>
using namespace std;
int sum(int x);
//MAIN STARTS
int main(){
cout<<"ENTER A NUMBER : ";
int a;
cin>>a;
cout<<"The required sum is : "<<sum(a)<<endl;
return 0;
}
// MAIN ENDS
int sum(int x){
if (x == 1)
return 1;
else
return ( x + sum (x-1));
}
Write a recursive function that computes the sum of all numbers from 1 to n , where n is given as parameter by the user.
*/
//CODE:
#include <iostream>
using namespace std;
int sum(int x);
//MAIN STARTS
int main(){
cout<<"ENTER A NUMBER : ";
int a;
cin>>a;
cout<<"The required sum is : "<<sum(a)<<endl;
return 0;
}
// MAIN ENDS
int sum(int x){
if (x == 1)
return 1;
else
return ( x + sum (x-1));
}
No comments:
Post a Comment