While loop introduction and basic Format (master):
Loop structure: when the conditions are met, the program repeats the conditions that make up the loop structure of a piece of code:1) cyclic control conditions 2 ) Loop body 3) Let the loop control condition be false to control the format of the while loop :while(expression) { statement block;
1#include <stdio.h>2 3 voidtest1 () {4 5 intI=1;6 7 //1) Cyclic control conditions8 while(i<= +){9 Ten //2) Circulation body Oneprintf"%d Times said: I love you!\n", i); A - //allows the loop control condition to be false -i = i+1; the - } - - + } - + voidtest2 () { A at //calculate the 1+2+3+.....+100 and - //defines a variable that stores the number of times the current period is executed - intI=1, sum=0; - intn=0; - //Suppose you enter a number from the keyboard to calculate the 1+2+3+....+n and -printf"Please enter a number: \ n"); in //accept a number from a keyboard -scanf"%d",&n); to + while(i<=N) { - the //value +i with the value of sum *sum = sum+i;//i = 1 sum = 1 $ //0+1, (0+1) +2Panax Notoginseng - //let the loop condition be false control the //i=i+1; +i++; A } the +printf"1+2+3+....+%d=%d\n", n,sum); - $ } $ - intMainintargcConst Char*argv[]) { - the test1 (); - Wuyi the return 0; -}
While loops use traps:
There is no statement that allows the loop control condition to be false
---------------------------------
Count the number of characters entered by the keyboard:
1#include <stdio.h>2 3 intMainintargcConst Char*argv[]) {4 5 //Defining Variables6 intCount=0;//used as a counter7 Charch;8 9 Ten //Accept Characters Onescanf"%c",&ch); A - //Loops - while(ch!='\ n') { the //Calculator +1 -count++; - //continue to remove one character - //the scanf principle, if the buffer is not empty, will not let the user enter the content again, + //and continue to get it directly from the buffer. -scanf"%c",&ch); //Quite brilliant thought, while constant judgment, equivalent to the outer multi-scanf statement only executes once + } A atprintf"count =%d\n", count); - - - return 0; -}
<08> While loop introduction and basic format +while loop using traps + statistics keyboard input characters +