Factorials to be re-written at while statement

Before I begin, I have to apologize again for leaving without any thanks to the previous threads I posted.
Moving on, here's a code for factorial notation using for statement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include<stdio.h>
main(){ 
int factorial = 1, num, i, x;

printf("\n\n\n\n\t\t\tEnter a number from 1 to 10:\t");
scanf("%d", &num);
if(num >= 1 & num <= 10)
{
     for(i = 1; i < num; i++)
     {
	 factorial = factorial * i;
           printf("%d x ", i);
     }
     x = factorial * num;
     printf("%d = %d", num, x);
}
else
{
     printf("ERROR! PLEASE TRY AGAIN");
}     
      getch();
}

As you can see, the program is fine. My friend and I experimented into this statement. Now we were to rewrite the program using while statement. We came up with this;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<stdio.h>
main(){ 
int factorial = 1, num, i, x;

printf("\n\n\n\n\t\t\tEnter a number from 1 to 10:\t");
scanf("%d", &num);
if(num >= 1 & num <= 10)
{
     while(i < num)
     {
	 factorial = factorial * i;
           printf("%d x ", i);
     }
     x = factorial * num;
     printf("%d = %d", num, x);
}
else
{
     printf("ERROR! PLEASE TRY AGAIN");
}     
      getch();
}

Surely, I know that for statement houses the format "for (initialize; condition; evaluate)" while the while statement has "while (condition). Now the weird part takes place, when we enter 1, it appeared like this

1x1x1x1x1 = 0.

We even tried different numbers only to arrive at the same conclusion. Is there anything wrong in the positioning?
First of all, in your if-statement you use the &-operator, which in this case is bitwise AND. You want to use && instead.

Your problem is that you don't initialize your index variable i.

This for-loop's equivalent:
1
2
for(int i=0; i < 10; ++i)
  // some task 


is this while-loop:
1
2
3
4
5
int i=0; // !!!
while(i < 10) {
  // some  task
  ++i;
}


What you miss is the line commented with !!!
Last edited on
so even if I miss the increment, what's more important is the one that is commented by !!! ?
Both are equally important. I just missed that you don't have an increment there. How did you while()-loop even terminate?
Last edited on
How did I while loop even terminate? Sorry, the question wasn't clear to me.
1
2
3
4
5
while(i < num)
{
  factorial = factorial * i;
  printf("%d x ", i);
}


In here you never change the value of i, which makes me think that this while()-loop will run infinitely.
Topic archived. No new replies allowed.