Control structures are fundamental building blocks for managing the flow of a program. They dictate the order in which statements are executed, enabling developers to make decisions, repeat tasks, and manage complex logic. Understanding control structures is essential for writing efficient and maintainable code.
By default, statements in C++ execute sequentially, one after the other. This is the simplest form of control flow.
These structures allow the program to make decisions and execute specific blocks of code based on conditions:
if
Statement: Executes code if a condition evaluates to true
.if-else
Statement: Executes one block if a condition is true
, and another if it’s false
.else if
Ladder: Checks multiple conditions sequentially.switch
Statement: Efficiently handles multi-way branching based on constant expressions.Loops allow repeated execution of a block of code:
for
Loop: Iterates a fixed number of times.while
Loop: Repeats while a condition is true
.do-while
Loop: Ensures the block executes at least once before checking the condition.Used for altering the normal flow of execution:
break
: Exits the nearest loop or switch
statement.continue
: Skips the rest of the current loop iteration and jumps to the next iteration.return
: Exits a function and optionally returns a value.goto
: Transfers control to a labeled statement (rarely used and discouraged).Here’s a small program that demonstrates selection and iteration:
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
if (n % 2 == 0) {
cout << n << " is even." << endl;
} else {
cout << n << " is odd." << endl;
}
cout << "Counting down from " << n << ":" << endl;
for (int i = n; i >= 0; i--) {
cout << i << " ";
}
cout << "Blast off!" << endl;
return 0;
}