prog. only accept integer from 0-10 then it's factorial It's running but it doesn't show the factorial What's wrong with this?

#include<iostream>
using namespace std;

int main()
{
int a[9],x,f=1;

cout<<"Please enter an integer [0-10 only] : ";
cin>>a[x];
for(x=0;x<=10;x++){
f*=a[x];}

for(x=0;x<=10;x++){
if (a>=0){
cout<<a<<"! is : "<<f<<endl;
}
else if (a<0){
cout<<"Out of Range!"<<endl;
}}


system ("pause");
return 0;
}
First,please always use code tags, select your code then press the <> button on the right.

cin>>a[x];

x is not initialised - garbage value.

This:
1
2
for(x=0;x<=10;x++){
f*=a[x];}


Over steps the array, use this instead:

1
2
for(x=0;x< 9;x++){
f*=a[x];}


Why have you got your input validation at the end of the program?

Hope all goes well.
Thank you sir. I'm sorry i'm just a newbie here that's why. That helped but sad to say, it shows wrong factorial.
Sorry - am not thinking straight (it's 04:20AM here in Melbourne, Australia)

1
2
for(x=0;x< 9;x++){
f*=a[x];}


Would equal 0, because the first one is 0 !!

Are you supposed to be showing all the factorials or just one?

1
2
for(x=1;x< 9;x++){ //factorial 8 - loop stops at 8
f*=x;}


if you want to show all of them, initialise the array with numbers 1 to 9, then use the for loop to calc each one & print it out.

There are lots of other algorithms for factorial on the web. If you have any trouble, just think about what is happening on every line of code.

Any way I am going to bed, before I mess up anything else :)
Topic archived. No new replies allowed.