简体   繁体   中英

Why the following program printing "Hello" three time and not two?

I am learning java nowadays, and while going through loops in java, I am stuck here, I am unable to understand why the following program is printing "Hello" three times. can you please explain?

public class Helloworld {

    public static void main(String[] args) {
        for (int i =1; i<=2; i++ ) {
            for (int j =1; j<=i ; j++) {
                System.out.println("Hello");        
            }   
        }
    }
}

for loop iterations:

i=1
    j=1 — prints "Hello"
    j=2 — breaks out of inner loop, `j <= i` is false.
i=2
    j=1 — prints "Hello"
    j=2 — prints "Hello"
    j=3 — breaks out of inner loop, `j <= i` is false.

This is what happens when the above code is run.

To understand why, change

System.out.println("Hello"); 

to

System.out.println("Hello: i = " + i + ", j = " + j); 

compile and run it again, and look carefully at the values of i and j printed out.

Basically, in the second iteration of the outer loop, the inner loop runs twice.


If you cannot compile and run the program, there is another way to understand the behavior. Hand execute it.

Get a pencil an piece of paper, draw a table with a column for each variable. Each time a variable is assigned to / modified (eg i = 0 or i++ ) add a new row to the table with the current values of all of the variables. When you have a test (eg i<=2 ) read the variable's value from the latest row in the table.

After some practice you will be able to do this in your head. After more practice you will be able to read the code (like you read English text, or mathematical notation) and reason about what the code does.

Or use a debugger :-)

Sometimes when learning loops, writing small loops on paper can help.

Here you habe a nested loop using variables i and j.

First, the inner loop, j=1, and 1 is less than or equal to 1(i), so it prints. Then j++.

j is now 2, which is not less than or equal to 1, ending inner loop cycle. Now back to outer loop, i++,

i is now 2. Inside the inner loop- j=1, less than or equal to 2, so second print. Now j++. Condition still true, as j(as 2) is still less than or equal to 2, so third print.

Hope this debugging method helps you.

You have two loops. The outer i loop runs twice, but inner j loop depends on the value of i with the j<=i part. So for the first i loop, j runs once, and the second i loop j runs twice, so three times all up.

This has to do with the nested looping. There's (2) loops to pay attention to here. For each iteration of the outer loop (i), the inner loop (j) may run multiple times. If you change the output to output the iterators, it will give you some visibility into this property.

System.out.println("i:"+i+"  j:"+j);

OUTPUT: $javac HelloWorld.java
i: 1  j:1
i: 2  j:1
i: 2  j:2

If you want to get a more detailed view on nested looping, here's a good video series I'd recommend: Nested Looping (The Coding Train)

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM