#TC1017 #WSQ09
This programm was very straightforward, since the formula to calculate the factorial is very simple, the tricky part was making the factorial function recursive, because it has to call itself with evey iteration in order to obtain the previous value given to n. In fact, this was my first use of recursion in this semester, that makes it noteworthy I think!
Source code below: [GitHub link: https://github.com/diegodamy/WSQ09 ]
#include <iostream>
using namespace std;
int factorial (int n){
if (n == 0){
return 1;
} else {
return n*factorial(n-1);
}
}
int main(){
int number;
char decision;
do {
cout << “To calculate the factorial, please enter the integer number:” << endl;
cin >> number;
if (number <0){
cout << “Please enter only positive numbers.” << endl;
cin >> number;
} else {
cout << “The factorial of ” << number << ” is ” << factorial (number) << endl;
}
cout << endl << “Would you like to calculate the factorial of another number? Y/N:” << endl;
cin >> decision;
cout << endl;
} while (decision == ‘Y’);
if (decision !=’Y’){
cout << “Thank you. Goodbye!”;
}
}
————–
Photo Credit: <a href=”https://www.flickr.com/photos/49968232@N00/6267826523/”>Leo Reynolds</a> via <a href=”http://compfight.com”>Compfight</a> <a href=”https://creativecommons.org/licenses/by-nc-sa/2.0/”>cc</a>