C++ if...else Statement
The if...else statement is a control structure in C++ that allows the program to execute different blocks of code based on different conditions. The syntax of the if...else statement is as follows:
if (condition) { // Code to execute when the condition is true } else { // Code to execute when the condition is false }
The condition is a boolean expression that evaluates to either true or false. If the condition is true, the code inside the if block is executed. If the condition is false, the code inside the else block is executed.
Here's an example of an if...else statement:
int x = 2; if (x > 5) { cout << "x is greater than 5" << endl; } else { cout << "x is less than or equal to 5" << endl; }
In this example, the condition x > 5
is false because x is equal to 2, which is less than 5. Therefore, the code inside the else block is executed and the message "x is less than or equal to 5" is printed to the console.
The if...else statement can also be extended with else if clauses to specify multiple conditions. Here's the syntax of an if...else if statement:
if (condition1) { // Code to execute when condition1 is true } else if (condition2) { // Code to execute when condition2 is true } else { // Code to execute when all conditions are false }
Here's an example of an if...else if statement:
int x = 7; if (x > 10) { cout << "x is greater than 10" << endl; } else if (x > 5) { cout << "x is greater than 5 but less than or equal to 10" << endl; } else { cout << "x is less than or equal to 5" << endl; }
In this example, the condition x > 10
is false, but the condition x > 5
is true. Therefore, the code inside the else if block is executed and the message "x is greater than 5 but less than or equal to 10" is printed to the console.