Cprogramming 简明教程

For Loop in C

包括 C 在内的多数编程语言都支持 for 关键字来构建循环。在 C 中,其他循环相关关键字是 whiledo-while 。与其他两种类型不同, for 循环被称为 automatic loop ,通常是程序员的首选。

Most programming languages including C support the for keyword for constructing a loop. In C, the other loop-related keywords are while and do-while. Unlike the other two types, the for loop is called an automatic loop, and is usually the first choice of the programmers.

for loop 是一个入口控制循环,它一直执行语句直到给定的条件。所有元素(初始化、测试条件和增量)被组合在一起,在带 for 关键字的圆括号内形成了 for loop

The for loop is an entry-controlled loop that executes the statements till the given condition. All the elements (initialization, test condition, and increment) are placed together to form a for loop inside the parenthesis with the for keyword.

Syntax of for Loop

C 编程语言中 for 循环语法:

The syntax of the for loop in C programming language is −

for (init; condition; increment){
   statement(s);
}

Control Flow of a For Loop

以下是 “for” 循环执行时的情况:

Here is how the control flows in a "for" loop −

init 步骤首先执行,只执行一次。此步骤允许你声明和初始化任何循环控制 variables 。可以不在这里放置语句,只要出现一个分号。

The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

接下来,对条件进行评估。如果为真,则执行循环体。如果为假,则不执行循环体,并且控制跳到 “for” 循环之后的下一条语句。

Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the control jumps to the next statement just after the "for" loop.

在执行 “for” 循环体之后,控制流跳回增量语句。此语句允许你更新任何循环控制变量。该语句可以留空,只要条件后面出现一个分号。

After the body of the "for" loop executes, the control flow jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.

现在重新评估条件。如果为真,则循环执行且进程重复自身(循环体,然后是增量步骤,然后再次是条件)。条件变为假后,“for” 循环终止。

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again the condition). After the condition becomes false, the "for" loop terminates.

Flowchart of for Loop

以下流程图表示 for 循环如何工作:

The following flowchart represents how the for loop works −

cpp for loop

当开发人员事先知道需要执行多少次迭代时,他们更喜欢使用 for 循环。可以将其视为对增量和测试循环变量的 whiledo-while 循环的一种简写。

Developers prefer to use for loops when they know in advance how many number of iterations are to be performed. It can be thought of as a shorthand for while and do-while loops that increment and test a loop variable.

for 循环可以用不同的变体应用。让我们了解 for 循环在不同情况下的工作原理。

The for loop may be employed with different variations. Let us understand how the for loop works in different situations.

Example: Basic for Loop

这是 for 循环的最基本形式。请注意,括号内的所有三个子句(在 for 关键字前面)都是可选的。

This is the most basic form of the for loop. Note that all the three clauses inside the parenthesis (in front of the for keyword) are optional.

#include <stdio.h>

int main(){
   int a;

   // for loop execution
   for(a = 1; a <= 5; a++){
      printf("a: %d\n", a);
   }

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

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

Initializing for Loop Counter Before Loop Statement

初始化步骤可以放在 for 循环标题上方。在这种情况下,必须通过放置一个分号使 init 部分留空。

The initialization step can be placed above the header of the for loop. In that case, the init part must be left empty by putting a semicolon.

Example

#include <stdio.h>

int main(){
   int a = 1;

   // for loop execution
   for( ; a <= 5; a++){
      printf("a: %d\n", a);
   }
   return 0;
}

你仍然得到相同的输出:

You still get the same output −

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

Updating Loop Counter Inside for Loop Body

你还可以放置空语句来代替增量子句。但是,需要将增量语句放置在循环体中,否则它将成为 infinite loop

You can also put an empty statement in place of the increment clause. However, you need to put the increment statement inside the body of the loop, otherwise it becomes an infinite loop.

Example

#include <stdio.h>

int main(){

   int a;

   // for loop execution
   for(a = 1; a <= 5; ){
      printf("a: %d\n", a);
      a++;
   }
   return 0;
}

这里,你也会得到与前一个示例中相同的结果:

Here too, you will get the same output as in the previous example −

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

Using Test Condition Inside for Loop Body

你还可以省略括号中测试条件的第二个子句。在这种情况下,你需要使用 break statement 终止循环,否则循环会无限运行。

You can also omit the second clause of the test condition in the parenthesis. In that case, you will need to terminate the loop with a break statement, otherwise the loop runs infinitely.

Example

#include <stdio.h>

int main(){
   int a;

   // for loop execution
   for(a = 1; ; a++){
      printf("a: %d\n", a);
      if(a == 5)
      break;
   }
   return 0;
}

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

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

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

Using for Loops with Multiple Counters

for 语句中,可能会对多个变量进行初始化和/或进行多个增量语句。但是,只能有一个测试条件。

There may be initialization of more than one variables and/or multiple increment statements in a for statement. However, there can be only one test condition.

Example

#include <stdio.h>

int main(){
   int a, b;

   // for loop execution
   for(a = 1, b = 1; a <= 5; a++, b++){
      printf("a: %d b: %d a*b: %d\n", a, b, a*b);
   }

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

a: 1 b: 1 a*b: 1
a: 2 b: 2 a*b: 4
a: 3 b: 3 a*b: 9
a: 4 b: 4 a*b: 16
a: 5 b: 5 a*b: 25

Decrement in for Loop

你还可以形成 for 递减循环。在这种情况下,循环变量的初始值大于其在测试条件中的值。for 语句中的最后一个子句使用递减运算符。

You can also form a decrementing for loop. In this case, the initial value of the looping variable is more than its value in the test condition. The last clause in the for statement uses decrement operator.

Example

以下程序按降序打印数字 5 到 1:

The following program prints the numbers 5 to 1, in decreasing order −

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

   // for loop execution
   for(a = 5; a >= 1; a--){
      printf("a: %d\n", a);
   }

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

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

Traversing Arrays with for Loops

For loop 非常适用于一次遍历数组的一个元素。请注意,数组中的每个元素都有一个从 “0” 开始的增量索引。

For loop is well suited for traversal of one element of an array at a time. Note that each element in the array has an incrementing index starting from "0".

Example

#include <stdio.h>

int main(){
   int i;
   int arr[] = {10, 20, 30, 40, 50};

   // for loop execution
   for(i = 0; i < 5; i++){
      printf("a[%d]: %d\n", i, arr[i]);
   }

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

a[0]: 10
a[1]: 20
a[2]: 30
a[3]: 40
a[4]: 50

Example: Sum of Array Elements Using for Loop

下面的程序计算给定数组中所有整数的平均值。

The following program computes the average of all the integers in a given array.

#include <stdio.h>
int main(){
   int i;
   int arr[] = {10, 20, 30, 40, 50};
   int sum = 0;
   float avg;

   // for loop execution
   for(i=0; i<5; i++){
      sum += arr[i];
   }
   avg = (float)sum / 5;
   printf ("Average = %f", avg);

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

Average = 30.000000

Example: Factorial Using for Loop

以下代码使用一个 for 循环计算一个数字的阶乘值。请注意,数字的阶乘是 1 和给定数字之间的所有整数的乘积。阶乘在数学上表示为以下公式:

The following code uses a for loop to calculate the factorial value of a number. Note that the factorial of a number is the product of all integers between 1 and the given number. The factorial is mathematically represented by the following formula −

x! = 1 * 2 * . . . * x

这是计算阶乘的代码:

Here is the code for computing the factorial −

#include <stdio.h>

int main(){

   int i, x = 5;
   int fact = 1;

   // for loop execution
   for(i=1; i<= x; i++){
      fact *= i;
   }
   printf("%d != %d", x, fact);

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

5! = 120

for 循环非常适用于已知重复次数的情况。然而,循环行为可以通过 for 循环主体内的 breakcontinue keywords 控制。在处理二级 arrays 时也经常使用嵌套 for 循环。

The for loop is ideally suited when the number of repetitions is known. However, the looping behaviour can be controlled by the break and continue keywords inside the body of the for loop. Nested for loops are also routinely used in the processing of two dimensional arrays.