Programme to find factorial of a number

I want to make a programme that finds the factorial of a number that i input: eg 6!=720.
The following is my source code, it can compile but the logic is probably wrong as it does not do what its suppose to do

#include<iostream>
using namespace std;

int factorial(int m){
int y,z;

for(z=1;z<=y;z++){
y=y*z;
return (y);




}
}

int main(){
int g,k;
cout<<"Enter a number";
cin>>g;
k=factorial(g);
cout<<"The answer is" << k;
system("PAUSE");
return 0;
}

1
2
3
4
5
6
7
8
9
10
11
int factorial(int m){
int y,z;

for(z=1;z<=y;z++){
y=y*z;
return (y);




}

y is not initialized (int y = 0;). I think you want to use m here
for(z=1;z<=m;z++)
what do you mean by y is not initialized???
Why did you declare parameter int m in your function
int factorial(int m); if it is not used?
sorry for my noobness i have no idea why i did it. My main aim is to create a factorial function and main function.I will then use the main function to call the factorial function and get the answer. Can someone show me the correct method to do it, thanks. I know i am half way there but i stilll cant solve it
Last edited on
For example you may use a recursive function:)

1
2
3
4
unsigned long long factorial( unsigned long long n )
{
	return ( ( n < 2 ) ? 1 : n * factorial( n - 1 ) );
}
factorial is calculated like this :-
for e.g 5.
5*4*3*2*1 = 120
initalize y with the number of which you want the factorial.
inside for loop,
initalize z equals to 1 less than y. decrement z and set the condition greater than or equal (>=) to 1.
the rest is correct.
Last edited on
This is what i got, but i am quite sure its wrong as the answer the programme gives is always wrong


#include<iostream>
using namespace std;

int factorial(int m){
int y,z,fact;
fact=1;

for(z=1;z<=y;z++){
fact=fact*z;
return (fact);




}
}

int main(){
int g;
cout<<"Enter a number";
cin>>g;

cout<<"The answer is" << factorial(g);
system("PAUSE");
return 0;
}

Topic archived. No new replies allowed.