Home > Backend Development > C++ > body text

A nested loop puzzle?

WBOY
Release: 2023-09-09 12:13:02
forward
550 people have browsed it

A nested loop puzzle?

In this section, we will see an interesting problem. We will see two code snippets. Both have two nested loops. We need to determine which one will run faster. (We will assume that the compiler does not optimize the code).

Code segment 1

for(int i = 0; i < 10; i++){
   for(int j = 0; j<100; j++){
      //code
   }
}
Copy after login

The Chinese translation of Segment 2

is:

paragraph 2

for(int i = 0; i < 100; i++){
   for(int j = 0; j<10; j++){
      //code
   }
}
Copy after login

Both segments of code will run the same number of times. The code inside the two loops will be executed 10000 times in both cases. But if we look closely, we can understand that the second piece of code does more tasks than the first piece of code. In the first piece of code, the inner loop will execute 10 times. Therefore, the initialization, condition check, and increment operations will be performed 10 times. But for the second piece of code, the inner loop will execute 100 times. Therefore, the initialization, condition checking and incrementing operations will be performed 100 times. So it will take longer than the first piece of code.

The above is the detailed content of A nested loop puzzle?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template