pointer
pointer

Reputation: 307

for loop in for loop without initialization

Here is my C code which I compiled and executed.

#include <stdio.h>

int main()
{
    unsigned i = 0, j = 0;
    unsigned s = 0;

    for (; i <= 1; i++)
        for (; j <= 1; j++)
            s++;

    printf("%u\n", s);
    return 0;
}

I expected to see 4, but I saw 2. I can not understand why?

Upvotes: 2

Views: 3851

Answers (5)

Arturouu
Arturouu

Reputation: 23

#include <stdio.h>
#include <conio.h>

int main()
{
   unsigned int i = 0, j = 0;
   unsigned int s = 0;

    for (; i <= 3; i++) //its supose to be 3 not 1 since its not going to add up to 4. 

    for (; j <= 3; j++)
        s++;

printf("%u\n", s);
getch();
return 0;

}

The problem was in the loops n_n !

Upvotes: 0

bergerg
bergerg

Reputation: 995

if you don't initialize j for the second time around your program wont execute the inner for-loop body.

and a tip - be explicit about your code. not only for the compiler to "understand" what you want but also for other programmers reading your code. in this code it is fairly obvious that

unsigned i

actually means

unsigned int i

but in another, bigger more complicated code it wont be so easy to guess.

Upvotes: 0

bolov
bolov

Reputation: 75698

It's in your title: you don't initialize j in the inner for.

So the sequence will be: (i,j):

0,0
0,1
0,2 (inner for won't enter body)
1,2 (inner for won't enter body)
2,2 (outer for won't enter body)

In situations like this, you should write on paper step by step each variable value and check every test. The next step is to learn how to use the debugger. It's immensely helpful and will spare you a lot of headaches. I can't emphasize enough how much easier your life will be made by a debugger.

Upvotes: 10

OldSchool
OldSchool

Reputation: 2183

Have a look here

firstly i=0;
then inner loop executes 2 times
for j=0 and j=1
now j becomes 2 and inner loop terminates
outer loop executes now for i = 1
but your inner loop has no initialisation so j would remain 2 and as a result inner loop never executs now aftet being executed for i=0

So solution is change inner loop as

for( j=0;j<=1;j++);

it will work now. Gud luck

Upvotes: 0

mah
mah

Reputation: 39807

The first i loop, j starts at 0, and ends at 2. The second i iteration, j is still 2, so you don't execute the j loop.

Upvotes: 4

Related Questions