Course Content
C++ Introduction
C++ Introduction
While Loop
We used if...else
, switch-case
to compare our variables with other values. But what if we need to do something a hundred times? A thousand times? A million times?
Loops are designed for just such cases! It allows you to loop your program under certain conditions. Structure of while loop:
main
#include <iostream> int main() { //x + y = result int x = 0; //root of equation int y = 8; int result = 1000; //increase x, until it satisfies the equation while (y + x != result) { x += 1; //x = x + 1 } std::cout << "Root of the equation: " << x; }
We have summed up (x+=1
) 992 times in this case. The loop ran while x + y
was not equal to result
(1000).
As soon as the expression x + y
became equal to result
, the loop ended, and we got the root of the equation (х
).
Note
The loop may not start if the condition is not satisfied.
It is crucial to make sure that the loop has an exit condition, that is, that the loop will not be infinite. The infinite loop example:
main
#include <iostream> int main() { bool condition = true; while (condition) { std::cout << "Loop is infinite!" << std::endl; } }
Thanks for your feedback!