07-25-2023, 11:00 AM
break is used to exit the loop prematurely, while continue is used to skip the current iteration and proceed to the next.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
printf("%d ", i);
}
// Output: 1 2 3 4
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the iteration when i is 3
}
printf("%d ", i);
}
// Output: 1 2 4 5
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
printf("%d ", i);
}
// Output: 1 2 3 4
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the iteration when i is 3
}
printf("%d ", i);
}
// Output: 1 2 4 5