#include <iostream>
int main() {
// Basic for loop
for (int i = 0; i < 5; i++) {
std::cout << "Iteration " << i << std::endl;
}
// For loop with different step
for (int i = 10; i >= 0; i -= 2) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
#include <iostream>
int main() {
int count = 0;
// Basic while loop
while (count < 5) {
std::cout << "Count: " << count << std::endl;
count++;
}
// While loop with condition
int number = 1;
while (number <= 10) {
if (number % 2 == 0) {
std::cout << number << " is even" << std::endl;
}
number++;
}
return 0;
}
#include <iostream>
int main() {
int choice;
do {
std::cout << "Enter 1-5 (0 to exit): ";
std::cin >> choice;
if (choice >= 1 && choice <= 5) {
std::cout << "You selected: " << choice << std::endl;
}
} while (choice != 0);
std::cout << "Goodbye!" << std::endl;
return 0;
}
#include <iostream>
int main() {
// Nested for loops for multiplication table
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
std::cout << i * j << "\t";
}
std::cout << std::endl;
}
// Pattern printing
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
std::cout << "* ";
}
std::cout << std::endl;
}
return 0;
}
#include <iostream>
int main() {
// Using break
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit loop when i equals 5
}
std::cout << i << " ";
}
std::cout << std::endl;
// Using continue
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
#include <iostream>
#include <vector>
#include <string>
int main() {
// Range-based for with array
int numbers[] = {1, 2, 3, 4, 5};
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
// Range-based for with vector
std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
for (const std::string& name : names) {
std::cout << "Hello, " << name << "!" << std::endl;
}
return 0;
}