# Thread: For Loop inside While Loop

1. ## For Loop inside While Loop

This simple loop construct is confusing me. I'm not seeing why the output is what it is. When I look at the code it seems like this should print one set of statements with x going from 0 to 4. Like this

x =1
-array[0] =1
-arrary[1] = 2

...and so on. why is this not the case?

Code:
```#include <stdio.h>

int main(void)
{
int array[5];
int i;
int x=0;
while(++x < 5) {
printf("*** x = %d\n",x);
for (i = 0; i < 5; i++) {
array[i] = x;
printf("\t - array[%d] = %d\n", i, array[i]);
}
printf("*** \n");
}
return 0;
}```
OUTPUT
Code:
```*** x = 1
- array[0] = 1
- array[1] = 1
- array[2] = 1
- array[3] = 1
- array[4] = 1
***
*** x = 2
- array[0] = 2
- array[1] = 2
- array[2] = 2
- array[3] = 2
- array[4] = 2
***
*** x = 3
- array[0] = 3
- array[1] = 3
- array[2] = 3
- array[3] = 3
- array[4] = 3
***
*** x = 4
- array[0] = 4
- array[1] = 4
- array[2] = 4
- array[3] = 4
- array[4] = 4
***```

2. Originally Posted by mesmer
why is this not the case?
Because x remains the same in the inner loop, so on each iteration of the for loop, you are assigning the same value of x to the corresponding element of the array named array.

It looks like you do not actually need x, since i serves the same purpose. You just need to make it such that you assign i+1 to the ith element of array. This also means that you only need a single loop, not nested loops.