Ad Code

Responsive Advertisement

C++ while loop - learn CPP

C++ while loop - learn CPPC++ provides a number of loops, or iterators, that are used to iterate parts of a program as needed. There are three types of loops in C++, which are for, while, and do while. In this article, we will talk about the first type, the while.


C++ while loop - learn CPP



while loop


It is an iterative phrase similar to the for repetition, used to repeat the steps of the software contained in its parentheses for a number of times, after examining the verification condition.

The way it is used is a bit similar to how the if keyword is used.


The general image for while:


The loop consists of the while keyword, followed by the recursion condition in parentheses, and then the statement if we want to execute a single statement.



while (condition)


statement;


And if we want to implement more than one statement, the general picture will be:



while (condition ){

statement 1;

statement 2;

...

statement n;

}

If the condition is true, the commands will be re-executed, and if it is false, the loop will be exited, meaning that the loop continues uninterrupted as long as the condition is satisfied.


The main point of the while loop is that the loop may not run at all when the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.


The execution of orders will be non-stop unless the condition becomes invalid, and if the condition is fixed or its value does not change, the orders will be executed an unlimited number of times, meaning that the execution of orders will remain uninterrupted, so we must use the effects of increase and decrease or give freedom The user can stop the loop whenever he wants.


The while loop allows the action of a part of the program to be repeated until a condition changes, for example:


while (x<50)

x=x*2


Here this loop will keep doubling the variable x until the value of x becomes greater than 50, at which point it stops. And in loops we always use variables, otherwise, the loop will be infinite, and the variable we will use is the counter of the loop, and we also have to give the variable a starting value.