Table of contents
Grammatical structures
while(expression)
loop statement;
Implementation process
example
Use a loop to print a to z
#include <stdio.h>
int main()
{
char i = 'a';//循环变量的初始化
while (i <= 'z')//判断
{
printf("%c ", i);
i++;//改变循环变量
}
return 0;
}
Results of the
After printing the value of i, be sure to change the value of i; if the value of i is not adjusted, the value of i will be a every time, and the program will become an endless loop
When using the while loop, be sure to adjust the value of the loop variable in the loop body
break statement in while loop
In the while, if the break statement is executed, it will jump out of the loop, that is, the following statement will not be executed
Note: if there is loop nesting, break only breaks out of the current loop , not all loops at once
continue statement in while
If the continue statement is executed in the while, the code behind the continue will not be executed, and the judgment part of the while statement will be skipped directly.
Application of while loop
1. Use the while loop to find the sum from 1 to n
#include <stdio.h>
int main()
{
int n = 0;
int sum = 0;
int i = 1;
printf("请输入一个数:>");
scanf("%d", &n);
while (i <= n)
{
sum += i;
i++;
}
printf("1到%d的和为: %d\n", n, sum);
return 0;
}
Note: When the number of iterations is uncertain or unknown, the while loop is preferred
2. Judging whether it is an adult
#include <stdio.h>
int main()
{
int age = 0;
while (1)//判断结果恒为真
{
scanf("%d", &age);
//当输入的值为-1时,结束循环
if (age == -1)
{
break;
}
if (age >= 18)
{
printf("成年\n");
}
else
{
printf("未成年\n");
}
}
return 0;
}