C language: Interpretation of the execution flow of nested for loops

 In order to better understand the execution flow of nested for loops

First of all, we need to know that for loop nesting generally means that the outer layer executes once, and the inner layer executes all

We use the following code to interpret

#include<stdio.h> 
int main(){ 
	for(int i=0;i<5;i++){
		i++;
		for(int j=0;j<3;j++){
			printf("%d",j);
			if(i>3)break;
		}
	} 
	return 0;
} 

Enter the outer loop i=0 i++

 Enter the inner loop j=0, output 0 , then i=1, then continue to output j=1, j=2   , and finally i=1, do not execute break, jump out of the outer loop

Back to the outer loop at this time i=1  Note: Here, the i++ of the outer loop must be executed first

Execute again i<5, at this time i=2 and then execute i++ in the fourth line

Enter the inner loop  j=0, output 0 , then i=3, then continue to output j=1, j=2   , and finally i=3, do not execute break, jump out of the outer loop

Back to the outer loop at this time i=3   Note: Here, the i++ of the outer loop must be executed first

Execute again i<5, at this time i=4 and then execute i++ in the fourth line

Enter the inner loop  j=0, output 0 , then i=5 and continue to execute if(i>3)break; break out of the outer loop

Back to the outer loop at this time i=5   Note: Here, the i++ of the outer loop must be executed first

Then execute i<5 and then i=6 to exit the outer loop (the outer loop ends, the inner loop must not be executed)

The final output is 012 012 0

If you have a certain foundation, you can see the following reasoning diagram

 

Guess you like

Origin blog.csdn.net/weixin_63987141/article/details/129140940