Factorial with while statement

This program reads a nonnegative integer then it should compute and print its factorial with while statement.
For example 5! 5*4*3*2*1=120
I get 0 as resoult. Can I get some help please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

int main(){
int n;
int x;
cout <<"Please enter an integer(-1 to quit):";
cin >> n;
x=n;
if(n>1){
    while(n>=1){
      n--;
      x=x*n;
    }
}
else if(n==1){
  x = 1;
}
else if(n==0){
  x = 0;
}
cout<<"n factorial: "<< x ;
}
  
  
Your loop goes one-too-far, ultimately multiplying the result by 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main() {
    while (true) {
        cout <<"Enter an integer(-1 to quit):";
        int n;
        cin >> n;
        if (n < 0)
            break;
        int f = 1;
        while (n > 1)
            f *= n--;
        cout << "n factorial: "<< f << '\n';
    }
}

Note that factorial(0) is 1, not 0.
Last edited on
Topic archived. No new replies allowed.