Anna Peng
Anna Peng

Reputation: 3

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");
    }

Upvotes: 0

Views: 176

Answers (2)

Priyanka Davle
Priyanka Davle

Reputation: 1

#include<iostream>
#include<string>
using namespace std;

void main()
{
    int n;
    int fact = 1;

    cout << "Enter any positive integer to get the factorial value...\n";
    cin >> n;
    if (n > 0)
    {
        for (int i = n; n > 0; n--)
        {
            cout << fact; 
            if (n > 0)
                cout << "*";
            fact = fact * n;
            cout << "Factorial of " << n << " is = " << fact << endl;
        }
    }
    else
        cout << "fact = 0"; 
}

Upvotes: 0

MrAbdul
MrAbdul

Reputation: 86

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

Upvotes: 1

Related Questions