Use when you know how many times to repeat a block of code
for (initialization; condition; update) {
// code block
}for (int i = 0; i < 5; i++) {
cout << i << " ";
}Use when the condition is checked before entering the loop
Here is this general structure of a while loop in a kotlin program.
while (condition) {
// code block
}int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}Executes at least once, then checks the condition
do {
// code block
} while (condition)int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);break exits the loop immediately:
for (int i = 0; i < 10; i++) {
if (i == 5) break;
cout << i << " ";
}continue skips the rest of the loop body and goes to the next iteration:
for (int i = 0; i < 5; i++) {
if (i == 2) continue;
cout << i << " ";
}for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
cout << i << "," << j << " ";
}
}This produces coordinate pairs.
while (true) {
// Loop forever unless break is used
}Be cautious — always include an exit condition eventually.
Ask the AI if you need help understanding or want to dive deeper in any topic