1

Very new to c++. Making this factorial program, and somehow I've scraped through the code and built something, but the value it returns is always 10 times the correct value. For example, factorial for 5 is computed at 1200 instead of 120, and factorial of 3 is computed at 60. Why the extra unit?

This is the code:

#include <iostream>

using namespace std;

int main() {

    int i, j, num;

    cout << "Compute factorial: " << endl;

    cin >> num;

    for (i=1; i<num; i++){

        for (j=num; j>1; j--)

            num *=(j-i);

        cout << num;
    }

    return 0;
}
1
  • Did any of the solutions below solve your problem?
    – starcodex
    Feb 25, 2014 at 2:17

5 Answers 5

1

All you need is one loop. This way should be much simpler.

#include <iostream>

using namespace std;

int main() {

    int i, j=1, num;

    cout << "Compute factorial: " << endl;

    cin >> num;

    for (i=num; i>0; i--){
        j *= i;
    }

    cout << j << endl;
}
0
for (i=1; i<num; i++){

     num *=i;
}

This should be enough

0

I think you are not quite clear about for loop,and be careful with the change of num try this piece of code, hope it will help

#include <iostream>

using namespace std;

int main() {

int i, j, num;

cout << "Compute factorial: " << endl;

cin >> num;
int output_num = 1;
for (i=1; i<=num; i++){

        output_num *= i;

}
cout << output_num;

return 0;
}
0

Use this code :

#include<iostream>
using namespace std;
int main()
{
int num,fact=1;
cout<<" Enter the no. to find its factorial:";
cin>>num;
for(int a=1;a<=num;a++)
{
fact=fact*a;
}
cout<<"Factorial of a given Number is ="<<fact<<endl;
return 0;
}

Output :

enter image description here

0

using two loops for computing factorial is very complex..... and you do not need it. Try this

#include <iostream>

using namespace std;

int main() {

    int i,num;
    cout << "Compute factorial: " << endl;
    cin >> num;
    for(i=num;i>1;--i)
        num*=(i-1);

        cout << num;

    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.