Introduction
Loops help repeat actions many times without writing the same code again and again.
Loops help repeat actions many times without writing the same code again and again.
for (initialization; condition; update) { // code to repeat } while (condition) { // code to repeat } do { // code to repeat } while (condition);
The for loop is good when you know how many times to repeat.
The while loop repeats as long as the condition is true.
for (int i = 1; i <= 5; i++) { std::cout << i << " "; }
int i = 1; while (i <= 5) { std::cout << i << " "; i++; }
int i = 1; do { std::cout << i << " "; i++; } while (i <= 5);
This program shows how each loop type repeats code to print numbers 1 to 3.
#include <iostream> int main() { std::cout << "For loop output: "; for (int i = 1; i <= 3; i++) { std::cout << i << " "; } std::cout << "\n"; std::cout << "While loop output: "; int j = 1; while (j <= 3) { std::cout << j << " "; j++; } std::cout << "\n"; std::cout << "Do-while loop output: "; int k = 1; do { std::cout << k << " "; k++; } while (k <= 3); std::cout << "\n"; return 0; }
Loops run the code inside their block repeatedly until the condition is false.
Be careful to update variables inside loops to avoid infinite loops.
Loops help repeat tasks easily and clearly.
Use for when you know how many times to repeat.
Use while or do-while when repeating depends on a condition.
for loop in C++?int count = 0;
for (int i = 1; i <= 3; i++) {
count += i;
}
std::cout << count;int i = 0;
while (i < 3) {
std::cout << i << " ";
}int sum = 0;
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) continue;
sum += i;
}
std::cout << sum;Pass the test and this pattern moves unknown