Write a Program to Implement Control Structures (if-else, switch-case, loops) in C++
Control structures in C++ are essential for managing the flow of a program. They help in making decisions and repeating tasks based on conditions. In this blog, we will cover three major control structures: if-else, switch-case, and loops (like for, while, and do-while), along with a practical example in C++.
Mastering these structures is fundamental for writing logical, structured, and dynamic code in C++.
🔹 Types of Control Structures
1. Conditional Statements
if-else**: Executes a block of code if a condition is true, otherwise executes another block.
2. Switch-Case
Allows selection among multiple code blocks based on a variable’s value.
3. Loops
- for: Executes a block of code a fixed number of times.
- while: Executes as long as a condition is true.
- do-while: Similar to while, but ensures at least one execution.
✅ C++ Program to Demonstrate All Control Structures
#include <iostream>
using namespace std;
int main() {
int choice, number;
// if-else statement
cout << "Enter a number: ";
cin >> number;
if (number % 2 == 0)
cout << "The number is even." << endl;
else
cout << "The number is odd." << endl;
// switch-case statement
cout << "\nMenu:\n1. Square\n2. Cube\nEnter your choice (1 or 2): ";
cin >> choice;
switch (choice) {
case 1:
cout << "Square of " << number << " is " << number * number << endl;
break;
case 2:
cout << "Cube of " << number << " is " << number * number * number << endl;
break;
default:
cout << "Invalid choice!" << endl;
}
// for loop
cout << "\nFirst 5 multiples of " << number << ": ";
for (int i = 1; i <= 5; i++) {
cout << number * i << " ";
}
// while loop
cout << "\n\nCountdown from 5 using while loop: ";
int count = 5;
while (count > 0) {
cout << count << " ";
count--;
}
// do-while loop
cout << "\n\nPrint number at least once using do-while loop: ";
int x = 0;
do {
cout << x << " ";
x++;
} while (x < 1);
return 0;
}
🔍 Output Explanation
Suppose the user enters `4`:
The number is even.
Menu:
1. Square
2. Cube
Enter your choice: 2
Cube of 4 is 64
First 5 multiples of 4: 4 8 12 16 20
Countdown from 5 using while loop: 5 4 3 2 1
Print number at least once using do-while loop: 0
Comments
Post a Comment