C++ If Statement
In C++, the if statement is used for conditional execution. It allows you to specify a block of code that is executed only if a certain condition is true. Additionally, you can use the else statement to specify an alternative block of code to be executed if the condition is false. The syntax for the if statement in C++ is as follows:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Here's a breakdown of the components:
-
condition: An expression that evaluates to either true or false. If the condition is true, the code within the first block is executed. If the condition is false, the code within the else block (if present) is executed.
-
Code to be executed: The block of code to be executed if the condition is true or false, depending on whether the else block is present or not.
Example 1: Simple If-Else Statement
int age = 20;
if (age >= 18) {
cout << "You are an adult." << endl;
} else {
cout << "You are a minor." << endl;
}
In this example, if the age variable is greater than or equal to 18, the message "You are an adult." will be printed. Otherwise, the message "You are a minor." will be printed.
Example 2: If Statement Without Else
int num = 10;
if (num > 0) {
cout < "The number is positive." < endl;
}
In this example, if the num variable is greater than 0, the message "The number is positive." will be printed. Since there is no else block, no code will be executed if the condition is false.
You can also use nested if statements or combine multiple conditions using logical operators (&& for logical AND, || for logical OR) to create more complex branching logic.
It's important to ensure that the condition within the if statement evaluates to either true or false. The code within the appropriate block will be executed based on the condition's result, providing you with the flexibility to control the flow of your program based on specific conditions.