简体   繁体   中英

Can anyone explain to me the behavior of a nested for loop in Java in regards to memory?

Let's suppose I have this code which also print a pattern of star (that is if I replace the string literal in side the print method with "#") like a staircase going from right to left below.

public static void main(String[] args) 
{
    for (int i=0; i <= 6; i++){
        for(int k=0; k < i; k++){
            System.out.print("This is k:"+k + " " + " This is i:"+i);
        }

        System.out.println();
    }


}

This will actually prints all 0s for the values of k in each column, then prints all 1s, then all 2s etc...For the value of i it will print in each column 1,2,3,4,5,6 then 2,3,4,5,6 the 3,4,5,6 etc..

Ok, why is the value of i does not start at zero here? I thought the inside loop is supposed to execute first.

This has nothing to do with memory, just logic. Because k starts at 0 , and k < i means the first test is 0 < 0 which isn't true. So i increments. Thus your first i output is 1 . If you want to see 0 for i , you need k <= i in your inner for loop condition.

Instead of this you should start your value of i from 1

for(i=1;i<6;i++)

As you are not achieving anything with i=0 except println .

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