The circular structure is a very important structure in the program. It is characterized by repeated execution of a section of a program when a given condition is established, until the condition is not tenable. Given conditions called cyclic conditions, repeated execution of the program segments is called the loop body. C language provides a variety of loop statements, which can form a variety of different forms of the loop structure.
While statement
The general form of a while statement is a while (expression) statement in which the expression is a loop condition and the statement is a loop body.
The semantics of the while statement is to evaluate the value of the expression and execute the Loop body statement when the duty is true (not 0). The execution process can be expressed in figure 3-4. Counts the number of line characters entered from the keyboard.
#include <stdio.h>
void main(){
int n=0;
printf("input a string:\n");
while(getchar()!='\n') n++;
printf("%d",n);
} int n=0;
printf("input a string:\n");
while(getchar()!='\n')
n++;
printf("%d",n);
The loop condition in this example program is GetChar ()!= ' \ n ', which means that as long as the character entered from the keyboard is not a carriage return, the loop continues. The loop body n++ completes the count of the number of input characters. The program implements a count of the number of characters entered for a single line of characters.
The following points should be noted when using the while statement:
An expression in a 1.while statement is typically a relational expression or a logical expression, and can continue looping as long as the value of the expression is true (not 0).
void main(){
int a=0,n;
printf("\n input n: ");
scanf("%d",&n);
while (n--)
printf("%d ",a++*2);
} int a=0,n;
printf("\n input n: ");
scanf("%d",&n);
while (n--)
printf("%d ",a++*2);
This example program will perform n cycles, each time, n value minus 1. The loop body outputs the value of an expression a++*2. The expression is equivalent to (a*2;a++)
2. If the circulation body includes more than one statement, it must be enclosed in {} to form a compound statement.
3. Attention should be paid to the choice of cyclic conditions to avoid dead loops.
void main(){
int a,n=0;
while(a=5)
printf("%d ",n++);
} int a,n=0;
while(a=5)
printf("%d ",n++);
In this case, the loop condition of the while statement is the assignment expression a=5, so the value of the expression is always true, and the loop body has no other means of stopping the loop, so the loop will go on endlessly, creating a dead loop. 4. The loop body of the while statement is allowed to be a while statement, thus creating a double loop.