Luca
Luca

Reputation: 13

Nested Loop Unexpected Behavior

I'm trying to debug my program with a nested loop to print out all the values in a 2d array. I was getting some unexpected behavior from the loop so i commented out some things and added a simple printf.

`int u = 0;
 int y = 0;
 char m = 'm';
 for (u; u < 12; u++)
 {
    printf("\n");
    for (y; y < 5; y++)
    {
        //transition[u][x] = &m;
        printf("o"); //this nested loop isnt working???? 
        //printf("%c", *transition[u][y]);
    }
 }`

Clearly this should print 12 rows of 5 'o's. But instead it is only printing out one row of 5 'o's followed by 11 newlines.

Edit: Thanks a lot! Silly mistake, I failed to realize that y would not set itself back to 0 on the second run through the loop. I guess overlooked this because I'm too used to Java initializing and setting the increment variable within the loop statement.

Upvotes: 0

Views: 328

Answers (3)

Pranay Soni
Pranay Soni

Reputation: 11

By looking at your question i assume that you are trying to print 5 o's in a line with 12 o's.

try this

for(u=0;u<12;u++)
{
    for(y=0;y<5;y++)
   {
         printf("o");
    }
    printf("\n");
}

Upvotes: 1

brichins
brichins

Reputation: 4055

You are not resetting y on your inner loop; try for (y = 0; y < 5; y++).

This will reset y at the beginning of each loop.

p.s. This is really more of a code review question

Upvotes: 1

Jack
Jack

Reputation: 133557

Your for initial statement doesn't mean anything:

for (y; y < 12; y++) 

The first statement is just y. Which has no side effects so you are not actually resetting y to 0 after first innermost loop. So from next iteration of outer loop, y == 5 and the inner loop is not executed at all.

You should do

for (y = 0; y < 12; y++)

Upvotes: 1

Related Questions