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