# What's wrong with this For Loop in C

This is a discussion on What's wrong with this For Loop in C within the C Programming forums, part of the General Programming Boards category; Code: #include<stdio.h> int main () { int i,number,factorial; printf("Enter the Number for Factorial\n"); scanf("%d",&number); for(i = 1;i <= number; i++) ...

1. ## What's wrong with this For Loop in C

Code:
```
#include<stdio.h>
int main ()

{
int i,number,factorial;

printf("Enter the Number for Factorial\n");

scanf("%d",&number);
for(i = 1;i <= number; i++)
{factorial = number*i;}

printf("\n %d ! = %d", number , factorial);

getch();

}```
I am new to Programming. I was trying to write a code to get factorials. It seems to me that the the above code doesn't work. What am i doing wrong?

2. factorial=factorial*i is what it should be or else you are just multiplying by number which is a constant.

EDIT: You should also initialize factorial to equal 1 before you use it. Otherwise it will be some gigantic random number.

3. Stop right there... "Doesn't work" is never an appropriate problem description.
Always describe the problem.

4. OK so... The 'for' loop "works" -> It does what it is told. The question is, what did you tell it to do?

Code:
```/* Let's say number = 8 */
for(i = 1;i <= number; i++)
{
factorial = number*i;
}

/* First loop */
// factorial = 8*1 = 8

/* Second loop */
// factorial = 8*2 = 16

/* Third loop */
// factorial = 8*3 = 24

/* Forth loop */
// factorial = 8*4 = 32

/* Fifth loop */
// factorial = 8*5 = 40

/* Sixth loop */
// factorial = 8*6 = 48

/* Seventh loop */
// factorial = 8*7 = 56

/* Eighth loop */
// factorial = 8*8 = 64

printf("\n %d ! = %d", number , factorial);

/* Prints "number ! = (number * number)" */
// 8 ! = 64```
What you need to do is work out an algorithm on paper and go though it like I just did.

5. Code:
```#include<stdio.h>
int main ()

{

int i, n, f=1;

printf("Enter the Number for Factorial\n");

scanf("%d",&n);

for(;i<=n;i++)
f*=i;
printf("\n Factorial is %ld", f);

getch();
}```

Thanks Click here, I think you are Right..but I got another way to do it. Thanks all for you responses. I will be more elaborate next time IMALC.

6. Code:
```int i, n, f=1;

printf("Enter the Number for Factorial\n");

scanf("%d",&n);

for(;i<=n;i++)
f*=i;```
Without the initial assignment of a value to i in the for loop, or before it starts, your program can't be seen as correct - it may work on your system, but it's not standard C, and will fail on other systems and compilers.

7. A few pointers
Code:
```#include <stdio.h>
int main (void)
{

int i=1, n;
long int f=1;

printf("Enter the Number for Factorial\n");

scanf("%d",&n);

for(;i<=n;i++)
f*=i;

printf("Factorial is %ld\n", f);

puts("Press Enter to continue...");
getchar();

return 0;
}```