简体   繁体   中英

How do you count how many times a nested for loop iterates?

In the code below, I can trace how many times each of the for loops iterate if I look at them separately. For example, both the for loops iterate 10 times however, when you put them together, the String "hi" prints out more than 20 times.

How many times does the inner loop iterate?

for(int j=0; j<10; j++) 
    for(int k=10; k>0; k--)
        System.out.println("hi");

It is as simple as multiplying how many each iterate together (in this case 10*10). If you are finding it isn't as simple as this, you can perform the following test:

int count = 0;
for(int j=0; j<10; j++){
    for(int k=10; k>0; k--){
        count++;
    }
}
System.out.println("The nested loop iterated " + String.valueOf(count) + " times!");

Edit: Perhaps an easier way to understand what is going on:

int total_count = 0;
for(int j=0; j<10; j++){
    System.out.println("The outer loop has iterated " + String.valueOf(j+1) + " times!"); 
    System.out.println("Executing the inner loop");   
    int local_count = 0;
    for(int k=10; k>0; k--){
        local_count ++;
        total_count ++;
        System.out.println("Inner loop #" + String.valueOf(j+1) + " has iterated " + String.valueOf(local_count) + " times!");
        System.out.println("The inner loop's total iterations are " + String.valueOf(total_count) + " times!");
    }
}
System.out.println("The nested loop iterated " + String.valueOf(total_count) + " times!"); 

When dealing with nested loops always try to visualize the first loop j as the row and the second loop k as the column.

在此处输入图片说明

The rows go left-to-right and the columns go top-to-bottom . If you multiply the row x column size then that is usually how many iterations you will encounter.

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