Doing factorials using C

lankygiant16

Baseband Member
Messages
63
So im taking this C programming class, and im not too great at programming, so im having a tough time. My teacher sucks, he doesnt really explain things very well, so we have to figure a lot stuff out. Im having trouble doing factorials...and yeah.

this is how i first took a stab at it

int i, num, factorial;

for( i=1; i<=num; i++)
{
factorial = num * i;
}

now i know this is wrong...just HOW WRONG am i? and how do i fix it. I also have to do summation meaning like 5+4+3+2+1 as an example....so i figure it will be quite similar. thanks for all the help!!

Jim
 
OK...

first think about what a factorial is...

1! = 1 = 1

2! = 2 x 1 = 2

3! = 3 x 2 x 1 = 6

so to find a factorial number you need to multiply all the numbers below it in sequence until you get to the at number...

for instance 4! = 1 * 2 * 3 * 4 = 24

so you just need a simple loop,
n = [start number];
factorial = 1;
for (i=1;i<=n;i++)
{
factorial = factorial * i;
}

n is the number that you start with
factorial is the total...

put the number 5 into the loop and you get something like...
n=5
(i=1) (factorial=1) -> (new factorial = 1*1 = 1)
(i=2) (factorial=1) -> (new factorial = 1*2 = 2)
(i=3) (factorial=2) -> (new factorial = 2*3 = 6)
(i=4) (factorial=6) -> (new factorial = 6*4 = 24)
(i=5) (factorial=24) -> (new factorial = 24*5 = 120)

now i=t so the loop stops and you have the numbers...
n=5
factorial = 120.
 
arg it still isnt working for me.....this is what i have typed in:


#include <stdio.h>

int main (void)
{
int fac=1, i, num;

printf( "Enter a number: ");
scanf( "%i\n", &num);

for(i=1; i<=num; i++);
{

fac = fac * i;

printf("\nFactorial of Num is %i\n", fac);
}
return 0;
}




and what happens is i get the Enter number...i enter the number....then the program does nothing, so i enter the number again, and it gives an answer of the number entered + 1. So like if i entered in 10, it'd say the factorial is 11....which is wrong...and i dont know why its just adding one AND why its not even doing the loop. PLEASE HELP!!!!!!!!
 
the problem is that you have a semi colon on the start of the loop line.

for(i=1; i<=num; i++);

remove that and it should all work fine.


#include <stdio.h>

int main (void)
{
int fac=1, i, num;

printf( "Enter a number: ");
scanf( "%i\n", &num);

for(i=1; i<=num; i++)
{
fac = fac * i;
}
printf("\nFactorial of Num is %i\n", fac);
return 0;
}
 
Back
Top Bottom