All lessons
LESSON 15/53Repeating Things
while Loops
GOALRepeat when you do not know how many times in advance.

while means "keep repeating while this stays true". If you forget to change the condition, it never stops!
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
int n = 3;
while (n > 0) {
cout << n << " ";
n--; // without this it never ends
}
cout << "Go!" << endl;
return 0;
}> what you see
3 2 1 Go!
//LINE BY LINE
Watch it run
The condition is checked first: 3 > 0 is true, so it enters the body.
for or while — which one?
- You know in advance how many turns →
for. - You loop until something happens →
while.
int n;
while (cin >> n) { // өгөгдөл дуустал
cout << n * n << " ";
}Infinite loops
If the condition never becomes false, the program loops forever. Usually it is because you forgot to change the counter.
int i = 0;
while (i < 5) {
cout << i;
// i++; ← мартсан! үүрд эргэнэ
}