Hi I'm trying to write a program that prints out a table of factorials in the range of 1 and 10 and the numbers cannot be negative. i almost have it done however the program isn't printing out the correct numbers. please help
Your indenting is off. It makes your code challenging to read. Do you use an ide?
Anyway, you might want to start by writing a simple factorial function. You can do it by loop or, in the classic example, by recursion. I will do it by loop just so you can see it more easily; do not just copy and paste this code as it is not quite relevant to your situation and I will be able to tell:
1 2 3 4 5 6 7 8 9
int factorial(int num)
{
if (num < 1)
return -1;
int ret = 1;
for (; num > 1; num--)
ret *= num;
return ret;
}
That should work about right.
Now then, write a function along those lines and just call it in a loop. Then show me the output.
By the way you can also write a factorial function recursively, but I really do not remember how to do it so don't ask me. A recursive function is a function that calls itself (ie quicksort).
Ok when I tried to follow your guild line and compiled my program i got 16384, 32768, 196608, 4718592, 566231040, 1073741824
I do not think I followed your example quite right and don't worry i didn't copy
en.wikipedia.org/wiki/IDE
And the reason it's not working is because you did not initialize fact. Therefore you get undefined behavior.
In addition fact will never equal zero because you are not reducing it. And why are you creating number = num when you already have the argument num?
i figured it out. the program was right but i wasn't resetting the value. and the reason that I had the int number; is because i used it as my number to go from 1 to 10 then terminate the loop. i guess your right that i dont need it but i couldnt think of a way to only use int num; . and thanks for helping :D
This code is shorter than the others.
for printing numbers higher than 10, change
i <= 10 to whatever you want (e.g. i <= 15).
#include <stdio.h>
int fact(int);
int main()
{
for (int i=1;i<=10;i++){
printf("%d ",fact(i));
}
getchar();
}
int fact(int n){
if (n==1)return 1;
else
return n*fact(n-1);
}