Reputation: 19
I don't understand this program, I don't get why number is initialized to 1 when the program takes user input. This is how I understand the program which is obviously wrong:
You enter the factorial number, lets says I enter 6, it goes to the while loop because 6 is greater than 1.
Now factorial
is 1, and number
is 6, 6 * 1 = 6
. Then 6 - 1 = 5
, so factorial
is 5 but i get 720 as output.
i don't think I understand the while loop
#include <iostream>
using namespace std;
int main()
{
// declaration of the variables
int factorial, number;
// initialization of the variables
factorial = 1;
number = 1;
// Prompt the user to enter the upper limit of integers
cout << "Please enter the number of the factorial";
cin >> number;
// using the while loop find out the factorial
while (number > 1)
{
factorial = factorial * number;
number = number - 1;
}
cout << "The factorial is " << factorial;
}
Upvotes: 0
Views: 136
Reputation: 761
The first thing I noticed was that there is an error in your code:
cout<<"The factorial is " < factorial;
should be:
cout<<"The factorial is " << factorial;
Correcting this should fix a compile error.
The essence of this code is:
int number
) from usernumber
Upvotes: 0
Reputation: 476920
The initial assignment of number
is indeed unnecessary. However, you should check the input operation for errors:
int factorial = 1;
int number;
if (!(std::cin >> number))
{
/* error! */
return 1; // i.e. abort the program
}
while (number > 1) { /* ... */ }
Upvotes: 1
Reputation: 25863
Your program works correctly.
6! = 6 * 5 * 4 * 3 * 2 = 720.
Btw, use recursion for such recursive problems.
#include <iostream>
using namespace std;
int main()
{
//declaration of the variabe
unsigned int number;
//prompt the user to enter the upper limit of integers
cout << "Please enter the number of the factorial";
cin >> number;
cout << factorial(number);
return 0;
}
unsigned int factorial(unsigned int n)
{
if (n <= 1)
{
return 1;
}
else
{
return n * factorial(n-1);
}
}
Upvotes: 2
Reputation: 13672
You are missing a "<" in last line of the program. It should be
cout<<"The factorial is "<<factorial;
After making this change when I compile and run the program it works for me correctly i.e computes the correct factorial. For example factorial of 5 i.e 5!=5*4*3*2*1=120
Upvotes: 2
Reputation: 10285
First of all, it is initialised to 1 because of the following condition:
Factorial(0) = 1
Factorial(1) = 1
So if a user inputs a number less than 2, you do not need some calculations, you just output 1
Upvotes: 0