Search code examples
c++factorial

C++ factorial program


I'm a starter in this language.. This is quite simple and yet I can't get it right,. need your help

This is what it should look like:

User enters a number, for example 5 and the result must be 120 (5 * 4 * 3 * 2 * 1)

This is my code:

#include<cstdlib>
#include<iostream>

    using namespace std;

    int main(){

    int num;
    int prod=0;

    cout<<"Enter a number: ";
    cin>>num;
    cout<<endl;

    if(num<1 || num>10){
        cout<<"Please enter a number from 1 to 10 only!";
    }
    else
    {
        for(int i=num;i>0;i--){
            cout<<i;
            if(i-1>0){
                cout<<"*";
                prod = prod * i;
            }

        }
        cout<<" = "<<prod;  
    }

    cout<<endl<<endl;   
    system("PAUSE");
    }

Solution

  • put prod = 1 instead of zero and that will solve your problem