Home > Backend Development > C++ > Usage and rules of for statement in C language

Usage and rules of for statement in C language

下次还敢
Release: 2024-04-29 21:54:18
Original
1076 people have browsed it

The for statement is a loop statement used to repeatedly execute a block of statements. Components: 1) Initialization: Executed at the beginning of the loop. 2) Condition: Check before each iteration; if true, continue, if false, end. 3) Increment: Executed after each iteration. Rules: 1) All three parts are legal C expressions. 2) Omitting the condition will result in an infinite loop by default. 3) If increment is omitted, the default is 1. 4) The scope of loop variables is limited to the for statement.

Usage and rules of for statement in C language

Usage of for statement in C language

The for statement is a loop statement that allows you to execute it repeatedly A series of statements.

For statement syntax:

<code class="c">for (initialization; condition; increment) {
  // 要重复执行的语句
}</code>
Copy after login

For statement components:

  • Initialization: Executed at the beginning of the loop. Usually used to set the initial value of loop variables.
  • Condition: Checked before each iteration. If true, the loop continues; if false, the loop ends.
  • Increment: Executed after each iteration. Usually used to update the value of a loop variable.

Rules for for statements:

  • The initialization, conditional, and increment parts can be any legal C expression.
  • If the condition part is omitted, the condition defaults to true, resulting in an infinite loop.
  • If the increment part is omitted, the increment defaults to 1.
  • The scope of loop variables is limited to the code block of the for statement.

Usage of the for statement:

The for statement can be used in a variety of situations, including:

  • Iterate over an array or string .
  • Repeat a block of code a specific number of times.
  • Control the step size of the loop.

Example:

<code class="c">// 遍历一个数组
int arr[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
  printf("%d ", arr[i]);
}

// 重复执行代码块 10 次
for (int i = 1; i <= 10; i++) {
  printf("执行第 %d 次\n", i);
}

// 控制循环的步长
for (int i = 0; i < 10; i += 2) {
  printf("%d ", i);
}</code>
Copy after login

The above is the detailed content of Usage and rules of for statement 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template