--Originally published at Solving problems with programming
This homework was a little bit more dificult for me at the biggining, i didn’t understand what was a recursion and how did they work. I wrote it just because a web page said how, but I didn’t understand how it worked. After analizing it finally i understood .
A recursion is the call of the same function that is being defined at that moment. You can define a function and at the same time use it inside that function. It is confusing to understand and to explain also hahaha, but in the code and by doing the exercise you could understarnd it.
int factorial(int n){
int resultado;
if(n>0)
resultado=n*factorial(n-1);
else if(n==0)
resultado=1;
return resultado;
I will simulate an exucution of this function. If n=2, n is bigger than 0 so, we will multiply n by the factorial of n-1 that equals 1. So the factorial of 1 is 1 multiply by the factorial of 1-1 that equals 0. So the factorial of 0 is 1, because that is said on the function, if(n==0) resultado=1. So 2*1*1 gives 2.
Here is all the code
#include <iostream>
using namespace std;
int factorial(int n){
int resultado;
if(n>0)
resultado=n*factorial(n-1);
else if(n==0)
resultado=1;
return resultado;
}
main(){
int num, res;
char op;
do{
cout<<“Escribe el número que desea convertir en factorial”<<endl;
cin>>num;
res = factorial(num);
if(res==0)
cout<<“No se puede sacar el factorial a numeros negativos “<<endl;
else{
cout<< “El número factorial es “<<res<<endl;
}
cout<<“¿Quieres calcular otro número factorial?(S/N)”;
cin>>op;
if(op==’N’||op==’n’)
cout<<“Ten un lindo día”<<endl;
}while(op==’S’||op==’s’);
return 0;
}
I also solve the factorial number with loops do while and for, that are easier to make. The code is linked if you like to take a look.