Skip to content

Latest commit

 

History

History
129 lines (85 loc) · 3.56 KB

File metadata and controls

129 lines (85 loc) · 3.56 KB

C for循环

原文: https://www.programiz.com/c-programming/c-for-loop

在本教程中,您将借助示例学习在 C 编程中创建for循环。

在编程中,循环用于重复代码块,直到满足指定条件为止。

C 编程具有三种循环类型:

  1. for循环
  2. while循环
  3. do...while循环

在本教程中,我们将学习for循环。 在下一个教程中,我们将学习whiledo...while循环。


for循环

for循环的语法为:

for (initializationStatement; testExpression; updateStatement)
{
    // statements inside the body of loop
}

for循环如何工作?

  • 初始化语句仅执行一次。
  • 然后,求值测试表达式。 如果测试表达式的计算结果为false,则for循环终止。
  • 但是,如果测试表达式的计算结果为true,则将执行for循环体内的语句,并更新更新表达式。
  • 再次求值测试表达式。

这个过程一直进行到测试表达式为假。 当测试表达式为false时,循环终止。

要了解有关测试表达式的更多信息(将测试表达式求值为真和假时),请查看关系式逻辑运算符


for循环流程图

Flowchart of for loop in C programming


示例 1:for循环

// Print numbers from 1 to 10
#include <stdio.h>

int main() {
  int i;

  for (i = 1; i < 11; ++i)
  {
    printf("%d ", i);
  }
  return 0;
} 

输出

1 2 3 4 5 6 7 8 9 10
  1. i初始化为 1。
  2. 计算测试表达式i < 11。 由于 1 小于 11 为真,因此执行for循环的主体。 这将在屏幕上打印 1i的值)。
  3. 执行更新语句++i。 现在,i的值为 2。再次,将测试表达式求值为true,并执行for循环的主体。 这将在屏幕上打印 2i的值)。
  4. 同样,执行更新语句++i,并求值测试表达式i < 11。 这个过程一直进行到i变为 11 为止。
  5. i变为 11 时,i < 11将为假,并且for循环终止。

示例 2:for循环

// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>
int main()
{
    int num, count, sum = 0;

    printf("Enter a positive integer: ");
    scanf("%d", &num);

    // for loop terminates when num is less than count
    for(count = 1; count <= num; ++count)
    {
        sum += count;
    }

    printf("Sum = %d", sum);

    return 0;
}

输出

Enter a positive integer: 10
Sum = 55

用户输入的值存储在变量num中。 假设用户输入了 10。

count初始化为 1,并求值测试表达式。 由于测试表达式count<=num(小于或等于 10 的 1)为真,因此将执行for循环的主体,并且sum的值将等于 1。

然后,执行更新语句++count,计数将等于 2。再次,对测试表达式进行求值。 由于 2 也小于 10,因此将测试表达式求值为true,并执行for循环的主体。 现在,sum等于 3。

继续进行此过程,并计算总和,直到count达到 11。

count为 11 时,测试表达式的计算结果为 0(假),并且循环终止。

然后,sum的值打印在屏幕上。


在下一个教程中,我们将学习while循环和do...while循环。