Conditional Statements
Conditional statements are an essential component of programming. They allow us to control the flow of execution based on certain conditions. In C++, there are two common types of conditional statements: if/else statements and switch case statements.
If/Else Statements
If/else statements are used to make decisions in a program based on a condition. The basic syntax of an if/else statement is as follows:
1#include <iostream>
2using namespace std;
3
4int main() {
5 int number = 5;
6
7 if (number > 0) {
8 cout << "Number is positive" << endl;
9 }
10 else {
11 cout << "Number is negative" << endl;
12 }
13
14 return 0;
15}
In this example, the program checks if the number
variable is greater than 0. If it is, the program outputs "Number is positive". Otherwise, it outputs "Number is negative".
Switch Case Statements
Switch case statements provide an alternative way to make decisions based on a condition. The basic syntax of a switch case statement is as follows:
1#include <iostream>
2using namespace std;
3
4int main() {
5 char grade = 'B';
6
7 switch (grade) {
8 case 'A':
9 cout << "Excellent" << endl;
10 break;
11 case 'B':
12 cout << "Good" << endl;
13 break;
14 case 'C':
15 cout << "Fair" << endl;
16 break;
17 default:
18 cout << "Invalid grade" << endl;
19 break;
20 }
21
22 return 0;
23}
In this example, the program checks the value of the grade
variable and executes the corresponding case based on the value. If none of the cases match, the default case is executed.
Conditional statements are powerful tools for controlling program flow and implementing different behaviors based on specific conditions. They are fundamental concepts in programming and are used in various real-world scenarios.