tinker101
tinker101

Reputation: 43

Java nested for loop

Here's what i don't understand as you can see my outer loop should only print 5 rows but when i add my inner loop it print 6 rows one blank and 5 0123 what happened here? why did my outer loop print 6 rows?

public static void main (String[] args) {


    int x;
    int y;

        for(x=1; x<=5; x++){
            System.out.println();
                for (y=0; y<4; y++){
                    System.out.print(y);
            }

        }

}

Upvotes: 0

Views: 163

Answers (5)

Brandon
Brandon

Reputation: 317

public static void main (String[] args) {
    //dont need to declare variables here. they can be declared in loop like below
    for(int x=0; x<5; x++){
        System.out.println(); //this is called before inner loop, printing a blank line
            for (int y=0; y<4; y++){
                System.out.print(y); //print 0-3 
        }
    }
}

If you want to print a blank line after the inner loop place the System.out.println() after the inner loop.

Stepping through the code with a debugger should have been your first troubleshooting step here. You should also standardise your loop variable checks like I have done above.

Upvotes: 1

BendyMan
BendyMan

Reputation: 301

your outer loop first prints a blank line, then 0123 on the next try

int x;
    int y;

        for(x=1; x<=5; x++){
                for (y=0; y<4; y++){
                    System.out.print(y);
            }
            System.out.println();

        }

Upvotes: 0

Pshemo
Pshemo

Reputation: 124275

Your first instruction in your outer loop is

System.out.println();

which means you are moving cursor to next line (leaving first line empty).

Then

for (y=0; y<4; y++){
    System.out.print(y);

happens which is responsible for printing 0123 in that line.

Then again in next iteration of outer loop cursor is moved to next line and 0123 is printed.

Consider moving System.our.println() at the end of your outer loop. This way you will let inner loop print 0123 first, before moving cursor to next line.

Upvotes: 0

mhawke
mhawke

Reputation: 87134

You are printing the new line before the actual output. Move System.out.println(); after the inner for loop:

public static void main (String[] args) {
    int x;
    int y;

    for(x=1; x<=5; x++){
        for (y=0; y<4; y++){
            System.out.print(y);
        }
        System.out.println();
    }
}

Output:

0123
0123
0123
0123
0123

Upvotes: 0

rgettman
rgettman

Reputation: 178313

The first thing the loop does is output a newline. Any characters printed in the y for loop after it appear on the next line. So, this prints 5 newlines, each followed by the y characters on the next line. The last iteration prints its characters on the 6th line, which follows the 5th newline character printed.

Move System.out.println() after the y for loop so it ends the line properly, after writing the characters.

Upvotes: 0

Related Questions