#include <iostream>
// A recursive function is a function calling itself
// A basecase is an ending point for the function
usingnamespace std;
int factorialFinder(int x);
int main(){
cout << "Enter a number: ";
cin >> factorialFinder();
cout << "Factoral is " << factorialFinder() << "\n";
return 0;
}
int factorialFinder(int x){
if (x == 1){
return 1; // basecase
}else{
return (x * factorialFinder (x - 1));
}
}
Factorial of a negative number !!! I hope you were kidding or being sarcastic
It seems that you have some problems with intellect. The function parameter is declared as int that is signed int. Nothing prevents to enter a negative number by the user. And what will you do?!
#include <iostream>
// A recursive function is a function calling itself
// A basecase is an ending point for the function
usingnamespace std;
int factorialFinder(int x);
int main(){
unsignedint num;
cout << "Enter a number: ";
cin >> num;
cout << "Factoral is " << factorialFinder(num) << "\n";
return 0;
}
int factorialFinder(int x){
if (x == 1){
return 1; // basecase
}else{
return (x * factorialFinder (x - 1));
}
}
#include <iostream>
// A recursive function is a function calling itself
// A basecase is an ending point for the function
usingnamespace std;
int factorialFinder(int x);
int main(){
unsignedint num;
cout << "Enter a number: ";
cin >> num;
cout << "Factoral is " << factorialFinder(num) << "\n";
return 0;
}
int factorialFinder(int x){
if (x <= 1){
return x; // basecase
}else{
return (x * factorialFinder (x - 1));
}
}
It seems that you have
some problems with
intellect.
I should rather say that.In my earlier post i have advised that he should change it to unsigned int(or as i said do a check for negative values) and as the lines he had asked me for i used unsigned int , so he had used it in his program.
#include <iostream>
int factorialFinder( int x );
int main()
{
constint MAX = 13 ; // largest number we can handle (implementation dependent)
int num;
std::cout << "Enter a number in : ";
std::cin >> num;
if( num < 0 ) std::cout << "factorial of a negative number is not defined\n" ;
elseif( num > MAX ) std::cout << "the factorial of " << num << " is too big\n" ;
else std::cout << "Factoral is " << factorialFinder(num) << '\n' ;
}
int factorialFinder( int x )
{
if( x==0 ) return 1 ;
elsereturn x * factorialFinder( x-1 ) ;
}
EDIT: Hadn't seen the post by amhndu.
To clarify: 'your code' in 'Try running your code' referred to the code DanielPatrick had posted.
amhndu's suggestion of 'check for negative values' is the sensible suggestion among the lot that were posted.