#C++ Control Flow
#Overview
Control flow statements determine the order in which statements are executed. C++ provides various control structures for decision making and looping.
#Conditional Statements
#if-else Statement
#include <iostream>
int main() {
int age = 18;
if (age < 13) {
std::cout << "Child" << std::endl;
} else if (age < 18) {
std::cout << "Teenager" << std::endl;
} else if (age < 65) {
std::cout << "Adult" << std::endl;
} else {
std::cout << "Senior" << std::endl;
}
return 0;
}#switch Statement
#include <iostream>
int main() {
char grade = 'B';
switch (grade) {
case 'A':
std::cout << "Excellent!" << std::endl;
break;
case 'B':
std::cout << "Good!" << std::endl;
break;
case 'C':
std::cout << "Average" << std::endl;
break;
case 'D':
std::cout << "Below Average" << std::endl;
break;
case 'F':
std::cout << "Fail" << std::endl;
break;
default:
std::cout << "Invalid grade" << std::endl;
}
return 0;
}#Looping Statements
#for Loop
#include <iostream>
int main() {
// Basic for loop
for (int i = 1; i <= 10; i++) {
std::cout << i << " ";
}
std::cout << std::endl;
// Range-based for loop (C++11)
int arr[] = {10, 20, 30, 40, 50};
for (int value : arr) {
std::cout << value << " ";
}
std::cout << std::endl;
return 0;
}#while Loop
#include <iostream>
int main() {
int count = 1;
while (count <= 5) {
std::cout << "Count: " << count << std::endl;
count++;
}
return 0;
}#do-while Loop
#include <iostream>
int main() {
int number;
do {
std::cout << "Enter a positive number (0 to exit): ";
std::cin >> number;
if (number > 0) {
std::cout << "You entered: " << number << std::endl;
}
} while (number != 0);
return 0;
}#Jump Statements
#break and continue
#include <iostream>
int main() {
// break example
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // exit loop
}
std::cout << i << " ";
}
std::cout << std::endl;
// continue example
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}#goto Statement (use sparingly)
#include <iostream>
int main() {
int count = 1;
start:
std::cout << "Count: " << count << std::endl;
count++;
if (count <= 5) {
goto start;
}
return 0;
}