0

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.

3 Answers 3

1

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++)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.