A loop lets you run a block of code over and over. Whether you're printing items from a list, tallying up a score, reading lines from a file, or running a game loop, skip the loop concept and your code will balloon into duplication.
cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
cout << "For loop count: " << i << endl;
}
int countdown = 3;
while (countdown > 0) {
cout << "Countdown: " << countdown << endl;
countdown--;
}
return 0;
}for loops have three parts: initialization, condition, and update. A while loop keeps running as long as its condition stays true. In the countdown example, leaving out countdown-- means the condition never stops being true — and you get an infinite loop.
You should see
For loop count: 1 For loop count: 2 For loop count: 3 Countdown: 3 Countdown: 2 Countdown: 1Info
If you know the number of iterations up front, use for; if it should keep running based on a condition instead, while is the better fit.