Factorial calculator

The image above is what my computer outputs when I run this program, a factorial calculator. 

It is a basic factorial calculator. The factorial of a number, lets say of number 5 (written 5!) is the multiplication of 5*4*3*2*1. The result of that operation would be 120.

In order to do this operation in C++, you have to use a loop or recursion. On my first try of this program I decided to use a For Loop. I´ll try to do it this weekend with recursion.

For this program to work, I created a function called “facto” with one parameter. The parameter is the number you want to get the factorial from.

So I declared an int variable called op and initialized it to 1. The operation inside the for loop is op = op * n, which is a number between 1 and a number less or equal to the required by the user, as you can see in my for loop.

int f, n, op =1;
char answer = ‘y’;

int facto(int x){

for (n = 1; n <= x; n++){

op = op * n;
}

return op;
}

A cool thing about this program is that it asks the user if he wants to repeat the process with another number, or if he wnats to end the program. I achieved this doing a do while loop.

Here you can have a look at my program:

WSQ09

And here is the code:

#include <iostream>
using namespace std;

int f, n, op =1;
char answer = ‘y’;

int facto(int x){

for (n = 1; n <= x; n++){

op = op * n;
}

return op;
}

int main(){

do {
cout << “Enter the number that you want to obtain the factorial from: ” << endl;

>> f;
cout << “The factorial of ” << f << “is equal to: ” << facto(f) << endl;
cout << “Do you want to try another number? (type y if you do, type anything else if not): ” << endl;
cin >> answer;

} while (answer == ‘y’);

cout << “Thanks for using my program!”;
}

Thanks for reading!

CC BY-SA 4.0 Factorial calculator by netosanchezb is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.