Branching and Looping Statements - 2

Old irons, this is the blogger's supplement to the previous article, I hope it will be helpful to you.

Article directory

One, for cycle

Two, do while loop

1. for loop

for(expression1; expression2; expression3)//syntax

       loop statement; 

expression 1

Expression 1 is the initialization part, which is used to initialize the loop variable.

expression 2

Expression 2 is the condition judgment part, which is used to judge the termination of the loop.

expression 3

Expression 3 is an adjustment part, which is used to adjust the loop condition.

Let's have a piece of code:

#include <stdio.h>//使用for循环 在屏幕上打印1-10的数字。
int main()
{
 int i = 0;
 //for(i=1/*初始化*/; i<=10/*判断部分*/; i++/*调整部分*/)
 for(i=1; i<=10; i++)
 {
 printf("%d ", i);
 }
 return 0;
}

The for loop first performs expression 1 to initialize the variable, then expression 2 judges whether to enter the loop, if it enters, executes the loop statement, and then expression 3 adjusts the loop condition.

The meaning of break and continue in a for loop is the same as in a while loop.

Regarding the while loop, you can look at my branch and loop statement - 1

But there are still some differences:

//代码1
#include <stdio.h>
int main()
{
 int i = 0;
 for(i=1; i<=10; i++)
 {
 if(i == 5)
 break;
 printf("%d ",i);
 }
 return 0;
}
//代码2
#include <stdio.h>
int main()
{
 int i = 0;
 for(i=1; i<=10; i++)
 {
 if(i == 5)
 continue;
 printf("%d ",i);
 }
 return 0;
}

 The continue in this code does not loop infinitely, but skips 5 and prints the following numbers.

Two, do while loop

do

      loop statement;

while(expression);

Features: The loop is executed at least once, and the scenarios used are limited, so it is not often used.

Let's look at the code

#include <stdio.h>
int main()
{
 int i = 10;
 do
 {
 printf("%d\n", i);
 }while(i<10);
 return 0;
}

Entering the loop first executes the loop statement once, and then judges whether to loop.

And break and continue can also be used in do while. Look at the following code

#include <stdio.h>
int main()
{
 int i = 10;
    
 do
 {
        if(5 == i)
            break;
 printf("%d\n", i);
 }while(i<10);
    
 return 0;
}
#include <stdio.h>
int main()
{
 int i = 10;
    
 do
 {
        if(5 == i)
            continue;
 printf("%d\n", i);
 }while(i<10);
    
 return 0;
}

Thank you for reading, I hope my article is helpful to you. If the blogger's article is helpful to you, please pay attention to it, like it, and support the blogger. Creation is not easy, thank you for your attention and praise.

Guess you like

Origin blog.csdn.net/LXW0403/article/details/130232208