Factorial

I was trying to develop a simple program that can calculate factorial, but i'm not getting the exact result that i want.
This was how i did it;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//expected result should be
//n*(n-1)*(n-2)*(n-3)...
//where n is the input value
#include<iostream.h>
#include<conio.h>
//definition of struct
struct factorial
{
long value;
long result;
long declaration;
}factorialresult;
int main()
{
clrscr();
//accepting input
cout<<"Enter value"<<endl;
cin>>factorialresult.value<<endl;
//declaration
for(factorialresult.declaration=(factorialresult.value-1); factorialresult.value<10; factorialresult.value++)
{
factorialresult.result=(factorialresult.declaration*factorialresult.declaration)
//printing the result
cout<<"Result is"<<endl;
cout<<factorialresult.result<<endl;
}
getch();

}


So how should go about it?
Last edited on
Something like:

1
2
3
4
5
factorialresult.result = 1;

for (int i = factorialresult.value; i > 0; --i) {
 factorialresult.result *= i;
}


Hi Zaita,
Please, i have tried it but i am still not getting the result. Thanks for your attention.
What you need to do is build your program step by step. Instead of trying to do it all at once.

For example: Do you really need to use a struct? In this situation it is adding un-necessary complexity to your application.

You should write you application in steps
1. Get the input from the user
2. Generate the factorial
3. Output the result.

Don't be afraid to put extra cout << statements in during the development to test that what your expecting is exactly what you're getting. My answer above gave you a simple formula in the form of a loop for generating the factorial.
I'm grateful Zaita, i will try your steps and then give you a feedback as soon as i'm through, have a blessed day.
Topic archived. No new replies allowed.