In C++, the if statement is used for conditional execution of code. The if statement evaluates a condition, and if the condition is true, it executes the code block enclosed within the curly braces { }. If the condition is false, the code block is skipped, and the program moves on to the next statement after the closing brace.
The syntax of the if statement is:
if (condition) { // code block }
Here, condition
is an expression that evaluates to a boolean value. If the value is true, the code block is executed, and if it is false, the code block is skipped.
Optionally, you can add an else
clause to the if statement, which is executed when the condition is false:
if (condition) { // code block if condition is true } else { // code block if condition is false }
You can also use multiple if statements to handle complex conditions.
Here is an example:
if (condition1) { // code block if condition1 is true } else if (condition2) { // code block if condition2 is true and condition1 is false } else { // code block if both condition1 and condition2 are false }
In this example, the first if statement is executed if condition1
is true. If it is false, the else-if statement is evaluated, and if condition2
is true, its code block is executed. If both condition1
and condition2
are false, the else block is executed.
Here’s an example of how the if statement works in C++:
#include <iostream> using namespace std; int main() { int num; cout << "Enter a number: "; cin >> num; if (num % 2 == 0) { cout << num << " is even." << endl; } else { cout << num << " is odd." << endl; } return 0; }
In this example, we first declare an integer variable num
and prompt the user to enter a number using cout
and cin
. Then, we use the if statement to determine whether the number entered by the user is even or odd.
The condition num % 2 == 0
checks whether the remainder of num
divided by 2 is equal to 0, which is true if num
is even. If the condition is true, the code block inside the curly braces is executed, which outputs a message indicating that the number is even.
If the condition is false (i.e., if num
is odd), the code block inside the else statement is executed, which outputs a message indicating that the number is odd.
Note that the if statement can be used with any Boolean expression, not just mathematical conditions. You can use logical operators (&&, ||, !) to combine multiple conditions or negations of conditions as well.