Input digit, find its factorial

i wrote a program here, its showin incorrect result..for its factorial ...
help me to fix it please..

#include <iostream>
using namespace std;

int main()
int n;
cout << "Input -> ";
cin >> n;

int f;
int count = 1;
while (count <= n)
f = f * count;
cout << f << endl;

return 0;
closed account (3qX21hU5)
int f;

f = f * count;

Your problem lies in these lines of code. Notice how you declare the integer "f" but never initialize it to anything. Which means we have no idea what number is stored in there.

You then go onto assign f * count to the variable "f". So since we don't know what number is in f to start with (It holds whatever was last in that memory location which will probably be random) we have idea what f * count equals (It could be 42 or it could be 4,565,665 we just don't know).

So to fix this problem you need to initialize the variable f to something. It is always a good idea to initialize all your variables to a default value unless you are absolutely sure that it won't be used until you have assigned something to it.
Last edited on
Take into account that if type int has size of 4 bytes then the maximum value for which the factorial can be stored in an object of type int is equal to 12.:)
Topic archived. No new replies allowed.