Hello, I’m Liang Tang.
While loops and do while loops are EasyC++.
For those who want a better reading experience, visit the Github repository.
The while loop
A while loop is a loop that has no conditional initialization and no conditional updates. It only has the test condition and the body of the loop. You can think of it as a for loop like this:
for(; i < n;) {}Copy the code
The while loop is written like this:
while (test-condition) {
body;
}
Copy the code
Inside the parentheses are the test conditions. When the test conditions are true, the loop executes and when the test conditions are false, it exits.
Obviously, if we do not change the conditional variables in the body of the loop, the loop will continue indefinitely and there is no way to exit. For example:
int i = 0;
while (i < 5) {
cout << "hello" << endl;
}
Copy the code
Since we haven’t changed the value of I in the body of the loop, it will never satisfy the exit condition >=5, so the loop will run indefinitely. Thus the loop that runs indefinitely becomes an infinite loop.
So in order for the loop to exit properly, we must remember to include logic in the body of the loop to ensure that the loop ends.
The do while loop
Unlike the for loop and the while loop, the do while loop is an exit condition, not an entry condition.
A do while loop executes the contents of the loop body before deciding whether to terminate. The for loop and the while loop execute the condition first, and then execute the loop body if the condition is satisfied. That is, a do while loop ensures that the body of the loop runs at least once.
do {
body;
} while (test-condition);
Copy the code
Scope-based for loops (C++11)
A new feature in C++11 allows for scope-based for loops, similar to those in Python. Such as:
double prices[5] = {1.0.2.3.3.5.6.1.2.1};
for (double x: prices) {
cout << x << endl;
}
Copy the code
So we’re going to use a variable x to go through all the elements in the prices array. Of course, the x obtained is a copy, equivalent to:
for (int i = 0; i < 5; i++) {
double x = prices[i];
}
Copy the code
If you want to change an element in the array, you can set it to a reference by adding an address character before x:
for (double &x : prices) {
x = 5.0;
}
Copy the code
So when we change x, we’re changing something in the array. This is a brief overview of the loop, and some of the technical details will be discussed in a later article.