Factorial function, loop doesn`t stop :/

Hi everyone! I started learning about c++ on my own, but at each step have a lot of problems...if someone could help me, I would be soo grateful. I tried to find out what`s wrong, but can`t find an answer.
so...

#include <iostream>
using namespace std;

int main() {
int i, n, fac = 1;
cout << "Enter a positive integer";
cin >> n;
for (i = n; i>1; i--) {

fac = fac * i;
cout << "Factorial is: " << fac << endl;
}
return 0;
}


Thanks!
Hi,

Think what your code does

firstly you have to check the for loop... the cout statement should be outside it

also instead of taking int you should take some other data type for factorial to calculate the factorial for bigger numbers

hope it helps
closed account (48T7M4Gy)
Within the limits of int capacity the program runs perfectly. Except maybe swap the last cout line and the following } line so that only the result is displayed.
i swaped it, but nothing changes... I don`t get one result at the end. The program just won`t stop.
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main() {
    int i, n, fac = 1;
    cout << "Enter a positive integer ";
    cin >> n;
    
    for (i = n; i>1; i--)
    {
        fac = fac * i;
    }
    cout << "Factorial is: " << fac << endl;
    return 0;
}


Enter a positive integer 7
Factorial is: 5040


Runs here perfectly including with the swap I mentioned. :)
Last edited on
I just copied this, and now it works! I don`t know why it doesn`t work when I type it by myself.... thank you, this little stupid thing took me a couple of days.
:)
closed account (48T7M4Gy)
Check it out but I copied your solution There was no magic, just luck maybe.
I know....really have no idea what`s going on, my compiler is bugging for some reason
closed account (48T7M4Gy)
Next time you re-compile use the "clean and rebuild option" which most menus have, maybe?
Rebuild all? I`ve tried that too now, and still, my version (which is as same as yours) doesn`t work xD
closed account (48T7M4Gy)
Try clean and rebuild. Maybe if you reboot/close and re-open the IDE might solve the problem.
Finally, it`s working! Thank you soo much :)
closed account (48T7M4Gy)
:)
Topic archived. No new replies allowed.