In the previous lesson, we introduced the for Loop in C ++. This tutorial introduces another loop statement While loop.
Let's look at another loop. The difference between it and the For loop is that the For loop generally knows the number of loops, which is indicated in the first line, while the while LOOP generally does not know the number of loops, let's take a look at an exercise;
1. Start Geany
1) Click "Application-programming-Geany" in the menu to start Geany and create a c ++ source program;
2) Click the "file-save as" command in the menu and save the file to your folder with "while" as the file name;
2. Enter the program code.
1) enter a program for summation. The process ends when the input is 0;
# Include <iostream>
Using namespace std;
Int main (int argc, char ** argv)
{
Int a = 0;
Int sum = 0;
Cout <"input a number :";
Cin>;
While (! = 0)
{
Sum = sum +;
Cout <"input a number :";
Cin>;
}
Cout <"sum =" <sum;
Return 0;
}
2) The first section defines two variables to store the input and sum,
The second paragraph first prompts you to enter a value,
The third part is a loop. In the brackets, first judge the value of a. If it is not 0, the sum is obtained. Then, enter, judge, and sum until the condition is not met and exit the loop,
The following section shows the final sum result;
3) Save, compile, generate, run, input the number continuously on the keyboard, and enter 0 at last to obtain the sum result;
3) The difference between the while loop and the for loop is that the while LOOP must first judge the condition and meet the recycling condition. It is generally used to read files and exit after reading the end Of the file;