ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Hi everyone,
I'm trying to write a program to calculate the factorial of a given integer. I would like to get some pointers on how to go about doing it. I was thinking of using a for loop but i haven't been able to put the right expressions in. here is where i am at so far:
#include <stdio.h>
int main(void)
{
int x;
printf("Enter number for factorial calculation: ");
scanf("%d", &x);
/*and here is where i am stuck*/
i well definitely appreciate any pointers in the right direction,
Thanks,
Randall
Think about the way you would calculate a factorial by hand. Say, 5 factorial. "Okay, that's 5x4x3x2x1." In other words, it's n times n-1 times n-2 ... all the way down to 1 (or 2, if you want to save the redundant step of multiplying by 1).
So you are on the right track with a for loop. How about, for i from n to 1, i = i - 1... multiply the total by i.
Thanks a lot!!
That really helped, i was getting really confused about the middle statement that terminated the loop, and i believe i made an error with the decrementation. i don't think i would have figured out the assignment of factorial *= (n -1); though
anyway, thanks a lot for the help, i really appreciate it,
i added a if statement to check for negetaive numbers so ... it works pretty well now.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.