简体   繁体   English

您如何计算嵌套的for循环迭代多少次?

[英]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循环迭代多少次。 For example, both the for loops iterate 10 times however, when you put them together, the String "hi" prints out more than 20 times. 例如,两个for循环都迭代10次,但是,当您将它们组合在一起时,字符串“ hi”将打印20次以上。

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). 只需将每个迭代的数量相乘(在这种情况下为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. 在处理嵌套循环时,始终尝试将第一个循环j视为行,将第二个循环k视为列。

在此处输入图片说明

The rows go left-to-right and the columns go top-to-bottom . left-to-right ,列top-to-bottom If you multiply the row x column size then that is usually how many iterations you will encounter. 如果将row x column大小相乘,则通常会遇到多少次迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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