What are the control statements that implement loop structures in C language?

青灯夜游
Release: 2020-07-21 10:24:34
Original
9842 people have browsed it

The control statements that implement loop structures in the C language include: while statement, do-while statement and for statement. The general form is "while (expression) {statement block}", "do {statement block} while (expression);", "for (expression 1; expression 2; expression 3) {statement block}".

What are the control statements that implement loop structures in C language?

The so-called loop (Loop) is to execute the same piece of code repeatedly. For example, to calculate the value of 1 2 3... 99 100, you must repeat 99 addition operation.

while loop

The general form of while loop is:

while(表达式){
    语句块
}
Copy after login

It means, first calculate the "expression" Value, when the value is true (not 0), execute the "statement block"; after executing the "statement block", calculate the value of the expression again, if it is true, continue to execute the "statement block"... This process will be repeated, Until the value of the expression is false (0), exit the loop and execute the code after the while.

We usually call the "expression" a loop condition and the "statement block" a loop body. The entire loop process is the process of constantly judging the loop condition and executing the loop body code.

Use a while loop to calculate the value of 1 added to 100:

#include <stdio.h>
int main(){
    int i=1, sum=0;
    while(i<=100){
        sum+=i;
        i++;
    }
    printf("%d\n",sum);
    return 0;
}
Copy after login

Running result:

5050
Copy after login

Code analysis:

1) When the program runs to while, because i=1 and i<=100 are true, the loop body will be executed; after the execution, the value of i changes to 2 and the value of sum changes to 1.

2) Next, we will continue to judge whether i<=100 is true, because at this time i=2, i<=100 is true, so we continue to execute the loop body; after the execution, the value of i becomes 3, sum The value becomes 3.

3) Repeat step 2).

4) When the loop reaches the 100th time, the value of i changes to 101 and the value of sum changes to 5050; because i<=100 is no longer true at this time, the loop is exited and the loop is no longer executed. body, and then execute the code behind the while loop.

The overall idea of ​​the while loop is as follows: Set a loop condition with variables, that is, an expression with variables; add an additional statement to the loop body so that it can change the loop condition The value of the variable. In this way, as the loop continues to execute, the values ​​of the variables in the loop condition will continue to change. There will eventually be a moment when the loop condition is no longer true and the entire loop ends.

What happens if the loop condition does not contain variables?

1) If the loop condition is true, the while loop will continue to execute and never end, becoming an "infinite loop". For example:

#include <stdio.h>
int main(){
    while(1){
        printf("1");
    }
    return 0;
}
Copy after login

When running the program, "1" will be output continuously until the user forces it to close.

2) If the loop condition is not true, the while loop will not be executed even once. For example:

#include <stdio.h>
int main(){
    while(0){
        printf("1");
    }
    return 0;
}
Copy after login

Run the program and nothing will be output.

Look at another example, count the number of characters entered in a line from the keyboard:

#include <stdio.h>
int main(){
    int n=0;
    printf("Input a string:");
    while(getchar()!=&#39;\n&#39;) n++;
    printf("Number of characters: %d\n", n);
    return 0;
}
Copy after login

Running result:

Input a string:c.biancheng.net↙
Number of characters: 15
Copy after login

The loop condition in this example program is getchar()!='\n', The meaning is that as long as the character entered from the keyboard is not a carriage return, the loop will continue. Loop body n;Complete counting the number of input characters.

do-while loop

In addition to the while loop, there is also a do-while loop in C language.

The general form of do-while loop is:

do{
    语句块
}while(表达式);
Copy after login

The difference between do-while loop and while loop is that it will execute the "statement block" first, and then Determine whether the expression is true. If it is true, continue the loop; if it is false, terminate the loop. Therefore, the do-while loop must execute the "block" at least once.

Use do-while to calculate the value of 1 added to 100:

#include <stdio.h>
int main(){
    int i=1, sum=0;
    do{
        sum+=i;
        i++;
    }while(i<=100);
    printf("%d\n", sum);
    return 0;
}
Copy after login

Running result:

5050
Copy after login
Copy after login

Notewhile(i<= 100);The final semicolon; is a must.

While loop and do-while have their own characteristics, you can choose appropriately. While loop is often used in actual programming.

In addition to the while loop, there is also a for loop in C language, which is more flexible in use and can completely replace the while loop.

for loop

Above we use the while loop to calculate the value of 1 added to 100, the code is as follows:

#include <stdio.h>
int main(){
    int i, sum=0;
    i = 1;  //语句①
    while(i<=100 /*语句②*/ ){
        sum+=i;
        i++;  //语句③
    }
    printf("%d\n",sum);
    return 0;
}
Copy after login

It can be seen that statements ①②③ are placed in different places, and the code structure is relatively loose. In order to make the program more compact, you can use a for loop instead, as shown below:

#include <stdio.h>
int main(){
    int i, sum=0;
    for(i=1/*语句①*/; i<=100/*语句②*/; i++/*语句③*/){
        sum+=i;
    }
    printf("%d\n",sum);
    return 0;
}
Copy after login

In the for loop, statements ①②③ are gathered together, and the code structure is clear at a glance.

The general form of the for loop is:

for(表达式1; 表达式2; 表达式3){
    语句块
}
Copy after login

Its running process is:

1) First execute "expression 1".

2) Execute "expression 2" again. If its value is true (non-0), execute the loop body, otherwise end the loop.

3) Execute "expression 3" after executing the loop body.

4) Repeat steps 2) and 3) until the value of "expression 2" is false, then end the loop.

In the above steps, 2) and 3) are a loop and will be executed repeatedly. The main function of the for statement is to continuously execute steps 2) and 3).

“表达式1”仅在第一次循环时执行,以后都不会再执行,可以认为这是一个初始化语句。“表达式2”一般是一个关系表达式,决定了是否还要继续下次循环,称为“循环条件”。“表达式3”很多情况下是一个带有自增或自减操作的表达式,以使循环条件逐渐变得“不成立”。

for循环的执行过程可用下图表示:

What are the control statements that implement loop structures in C language?

我们再来分析一下“计算从1加到100的和”的代码:

#include <stdio.h>
int main(){
    int i, sum=0;
    for(i=1; i<=100; i++){
        sum+=i;
    }
    printf("%d\n",sum);
    return 0;
}
Copy after login

运行结果:

5050
Copy after login
Copy after login

代码分析:

1) 执行到 for 语句时,先给 i 赋初值1,判断 i<=100 是否成立;因为此时 i=1,i<=100 成立,所以执行循环体。循环体执行结束后(sum的值为1),再计算 i++。

2) 第二次循环时,i 的值为2,i<=100 成立,继续执行循环体。循环体执行结束后(sum的值为3),再计算 i++。

3) 重复执行步骤 2),直到第101次循环,此时 i 的值为101,i<=100 不成立,所以结束循环。

由此我们可以总结出for循环的一般形式:

for(初始化语句; 循环条件; 自增或自减){
    语句块
}
Copy after login

for循环中的三个表达式

for 循环中的“表达式1(初始化条件)”、“表达式2(循环条件)”和“表达式3(自增或自减)”都是可选项,都可以省略(但分号;必须保留)。

1) 修改“从1加到100的和”的代码,省略“表达式1(初始化条件)”:

int i = 1, sum = 0;
for( ; i<=100; i++){
    sum+=i;
}
Copy after login

可以看到,将i=1移到了 for 循环的外面。

2) 省略了“表达式2(循环条件)”,如果不做其它处理就会成为死循环。例如:

for(i=1; ; i++) sum=sum+i;
Copy after login

相当于:

i=1;
while(1){
    sum=sum+i;
    i++;
}
Copy after login

所谓死循环,就是循环条件永远成立,循环会一直进行下去,永不结束。死循环对程序的危害很大,一定要避免。

3) 省略了“表达式3(自增或自减)”,就不会修改“表达式2(循环条件)”中的变量,这时可在循环体中加入修改变量的语句。例如:

for( i=1; i<=100; ){
    sum=sum+i;
    i++;
}
Copy after login

4) 省略了“表达式1(初始化语句)”和“表达式3(自增或自减)”。例如:

for( ; i<=100 ; ){
    sum=sum+i;
    i++;
}
Copy after login

相当于:

while(i<=100){
    sum=sum+i;
    i++;
}
Copy after login

5) 3个表达式可以同时省略。例如:

for( ; ; )  语句
Copy after login

相当于:

while(1)  语句
Copy after login

6) “表达式1”可以是初始化语句,也可以是其他语句。例如:

for( sum=0; i<=100; i++ )  sum=sum+i;
Copy after login

7) “表达式1”和“表达式3”可以是一个简单表达式也可以是逗号表达式。

for( sum=0,i=1; i<=100; i++ )  sum=sum+i;
Copy after login

或:

for( i=0,j=100; i<=100; i++,j-- )  k=i+j;
Copy after login

8) “表达式2”一般是关系表达式或逻辑表达式,但也可是数值或字符,只要其值非零,就执行循环体。例如:

for( i=0; (c=getchar())!=&#39;\n&#39;; i+=c );
Copy after login

又如:

for( ; (c=getchar())!=&#39;\n&#39; ; )
    printf("%c",c);
Copy after login

相关推荐:《c语言教程

The above is the detailed content of What are the control statements that implement loop structures in C language?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!