Archived

This topic is now archived and is closed to further replies.

bioagentX

Factorial # program

Recommended Posts

I''m trying to create a factorial number program where a user inputs a factorial number, like 9!, and the program outputs the value. Could someone please tell me how to code the for loop part?

Share this post


Link to post
Share on other sites
Show us the code you''ve already written, and explain where you are stuck. Do you know how to code a for loop?

Share this post


Link to post
Share on other sites

      
int n = 9; // Inputed value

// Error checking goes here

int f = 1; // result

for (int i=2; i <= n; i++) {
f *= i;
}

// output f



This is basically how you would expand it manually, so the algorithm should be obvious unless you are just learning.

Of course there are probably faster methods.
[EDIT] Oh, if this is homework, you should be beat over the head. That's meant as a joke of course...if this really is homework you should read the FAQ

[edited by - Thunder_Hawk on May 6, 2003 6:47:40 PM]

Share this post


Link to post
Share on other sites
Here is the code



#include


int main()
{

cout<<"-------------------------Factorial Number Program--------------------"< cout<<"This is the factorial number program, enter a number \n to find it''s factorial value: ";
int n;
cin>>n;
cout< int total;


for (int i=n; i; i--)

{



total*=i;






}

cout< cout<<"The factorial value you entered is equal to \n "< return 0;


}

Share this post


Link to post
Share on other sites
The condition for your for statement should be i > 1. BTW, please modify your post with the source tags ([ source ]/*code goes here*/ [ /source ] minus the spaces), it was seriously misinterpreted.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
if he uses:

for(int i = 0; i <= n; i++)

the result will be 0. It should be:

for(int i = 1; i <= n; i++)

instead.

Share this post


Link to post
Share on other sites