Cprogramming 简明教程

C - Loops

Loops 是一个编程构造,表示一个或多个语句的块,这些语句会重复执行指定次数,或者直到满足某个条件。

Loops are a programming construct that denote a block of one or more statements that are repeatedly executed a specified number of times, or till a certain condition is reached.

重复任务在编程中很常见,循环对于节省时间和最大程度减少错误至关重要。在 C programming 中,提供了 whiledo–whilefor 关键字来实现循环。

Repetitive tasks are common in programming, and loops are essential to save time and minimize errors. In C programming, the keywords while, do–while and for are provided to implement loops.

循环构造是任何处理逻辑的重要组成部分,因为它们有助于重复执行同一过程。C 程序员应该非常熟悉实现和控制循环构造。

Looping constructs are an important part of any processing logic, as they help in performing the same process again and again. A C programmer should be well acquainted with implementing and controlling the looping construct.

编程语言提供了各种控制结构,允许执行更复杂的执行路径。循环语句允许我们多次执行一条语句或一组语句。

Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times.

Flowchart of C Loop Statement

下面给出了适用于任何编程语言的循环语句的一般流程图 -

Given below is the general flowchart of a loop statement which is applicable to any programming language −

loop architecture

C 程序中的语句总是自上而下执行。如果我们要求编译器返回到任何前面的步骤,它将构成循环。

The statements in a C program are always executed in a top-to-bottom manner. If we ask the compiler to go back to any of the earlier steps, it constitutes a loop.

Example: Loops in C

为了理解程序中循环的必要性,请考虑以下代码段 -

To understand the need of loops in a program, consider the following snippet −

#include <stdio.h>
int main (){

   // local variable definition
   int a = 1;

   printf("a: %d\n", a);
   a++;

   printf("a: %d\n", a);
   a++;

   printf("a: %d\n", a);
   a++;

   printf("a: %d\n", a);
   a++;

   printf("a: %d\n", a);

   return 0;
}

Output

运行此代码,您将获得以下输出−

On running this code, you will get the following output −

a: 1
a: 2
a: 3
a: 4
a: 5

此程序打印“a”的值,并对其值进行递增。重复这两个步骤多次。如果您需要打印“a”值从 1 到 100,最好不要手动在代码中重复这些步骤。相反,我们可以要求编译器重复执行打印和递增这两个步骤,直到达到 100。

The program prints the value of "a", and increments its value. These two steps are repeated a number of times. If you need to print the value of "a" from 1 to 100, it is not desirable to manually repeat these steps in the code. Instead, we can ask the compiler to repeatedly execute these two steps of printing and incrementing till it reaches 100.

Example: Using While Loop in C

可以使用 forwhiledo-while 构造重复循环。以下程序演示如何使用 C 中的“while”循环打印 100 个“a”值 -

You can use for, while or do-while constructs to repeat a loop. The following program shows how you can print 100 values of "a" using the "while" loop in C −

#include <stdio.h>

int main () {

   // local variable definition
   int a = 1;

   while (a <= 100){
      printf("a: %d\n", a);
      a++;
   }

   return 0;
}

Output

运行此代码并检查输出 −

Run this code and check the output −

a: 1
a: 2
a: 3
a: 4
.....
.....
a: 98
a: 99
a: 100

如果某个步骤根据任何条件将程序流重定向到任何前面的步骤,那么该循环就是条件循环。一旦控制条件变为 false,重复将停止。如果重定向执行时没有任何条件,它就是一个 infinite loop ,因为代码块会一直重复。

If a step redirects the program flow to any of the earlier steps, based on any condition, the loop is a conditional loop. The repetitions will stop as soon as the controlling condition turns false. If the redirection is done without any condition, it is an infinite loop, as the code block repeats forever.

Parts of C Loops

为了构成循环,以下元素是必要的 -

To constitute a loop, the following elements are necessary −

  1. Looping statement (while, do–while or for)

  2. Looping block

  3. Looping condition

循环通常分为两种类型 -

Loops are generally of two types −

Counted Loops in C

如果循环设计为重复一定次数,则它是一个计数循环。在 C 中, for 循环是计数循环的示例。

If the loop is designed to repeat for a certain number of times, it is a counted loop. In C, the for loop is an example of counted loop.

Conditional Loops in C

如果循环设计为重复,直到某个条件为 true,则它是一个条件循环。 whiledo–while 构造有助于形成条件循环。

If the loop is designed to repeat till a condition is true, it is a conditional loop. The while and do–while constructs help you to form conditional loops.

Looping Statements in C

C 编程提供以下类型的循环来处理循环需求 −

C programming provides the following types of loops to handle looping requirements −

Sr.No.

Loop Type & Description

1

while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

2

for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

3

do-while loop It is more like a while statement, except that it tests the condition at the end of the loop body.

4

nested loops You can use one or more loops inside any other while, for or do-while loop.

上述每种循环类型都必须根据哪种类型适合给定情况来使用。我们将在后续章节中详细了解这些循环类型。

Each of the above loop types have to be employed depending upon which one is right for the given situation. We shall learn about these loop types in detail in the subsequent chapters.

Loop Control Statements in C

循环控制语句会更改从其正常序列执行。当执行离开作用域时,在该作用域中创建的所有自动对象都会被销毁。

Loop control statements change the execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C 支持以下控制语句 −

C supports the following control statements −

Sr.No.

Control Statement & Description

1

break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

2

continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

3

goto statement Transfers the control to the labeled statement.

breakcontinue 语句具有对比目的。 goto 语句充当跳转语句,如果它导致程序转到后面的语句。如果 goto 语句将程序重定向到前面的语句,则它会形成一个循环。

The break and continue statements have contrasting purposes. The goto statement acts as a jump statement if it causes the program to go to a later statement. If the goto statement redirects the program to an earlier statement, then it forms a loop.

The Infinite Loop in C

如果条件从未变为假,则循环将变为 infinite loop 。一个无穷循环是一个无限期重复的循环,因为它没有终止条件,或者永远不满足终止条件,或者指示循环重新从头开始。

A loop becomes an infinite loop if a condition never becomes false. An infinite loop is a loop that repeats indefinitely because it has no terminating condition, or the termination condition is never met or the loop is instructed to start over from the beginning.

尽管程序员有可能故意使用无穷循环,但它们常常是新程序员犯的错误。

Although it is possible for a programmer to intentionally use an infinite loop, they are often mistakes made by new programmers.

Example: Infinite Loop in C

for 循环传统上用于创建无穷循环。由于组成“for”循环的三个表达式都不是必需的,因此您可以通过清空条件表达式来创建一个无限循环。

The for loop is traditionally used for creating an infinite loop. Since none of the three expressions that form the "for" loop are required, you can make an endless loop by leaving the conditional expression empty.

#include <stdio.h>

int main (){

   for( ; ; ){
      printf("This loop will run forever. \n");
   }

   return 0;
}

通过运行此代码,您将获得一个不断打印同一行的无穷循环。

By running this code, you will get an endless loop that will keep printing the same line forever.

This loop will run forever.
This loop will run forever.
........
........
This loop will run forever.

当不存在条件表达式时,假定它为真。您可能有一个初始化和增量表达式,但 C 程序员更常用 for(;;) 结构来表示一个无穷循环。

When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.

Note − 您可以通过按下“ Ctrl + C ”键来终止无穷循环。

Note − You can terminate an infinite loop by pressing the "Ctrl + C" keys.