[C language learning notes]: Summary of loop statements

Nesting of loops in C language

A loop body contains another complete loop structure, which is called loop nesting. Loops can also be nested within an embedded loop body, which is a multi-level loop.

Three commonly used loop statements: while statement, do...while statement and for statement can be nested in each other.

Comparison of loops in C language

  • All three types of loop statements can be used to deal with the same problem, and generally they can replace each other.

  • In the while statement and do...while statement, the loop condition is specified only in the parentheses after while. Therefore, in order for the loop to end normally, the statement that causes the loop to end should be included in the loop body.

  • When using while and do...while statements, the loop variable initialization operation should be completed before the while and do...while statements.

  • While statements, do...while statements and for statements can all use the break statement to jump out of the loop, and the continue statement to end the current loop.

C language changes the state of a loop

1. C language uses the break statement to terminate the loop early

General form
 break;

Its function is to make the process jump outside the loop body, and then execute the statements below the loop body.

The break statement can only be used in loop statements and switch statements, and cannot be used alone.

2. C language uses the continue statement to end this loop in advance.

General form
continue;

Its function is to end this loop, that is, skip the unexecuted statements below in the loop body and go to the end point of the loop body.

3. The difference between break and continue

  • The continue statement only ends this loop, not the execution of the entire loop.

  • The break statement ends the entire loop process and no longer determines whether the conditions for executing the loop are established.

C language uses break statement

#include<stdio.h>
int main()
{
  int i;
  for(i=0;i<10;i++)
  {
    if(i==5)
    {
      break;
    }
    printf("%d\n",i);
  }
  return 0;
}

Compile and run results:

0
1
2
3
4

--------------------------------
Process exited after 0.07831 seconds with return value 0Please
press any key continue. . .

C language uses continue statement

#include<stdio.h>
int main()
{
  int i;
  for(i=0;i<10;i++)
  {
    if(i==5)
    {
      continue;
    }
    printf("%d\n",i);
  }
  return 0;
}

Compile and run results:

0
1
2
3
4
6
7
8
9

--------------------------------
Process exited after 0.073 seconds with return value 0
Please press any key to continue. . . .

Guess you like

Origin blog.csdn.net/Jiangziyadizi/article/details/129638597