In C++, the if else
statement is used for conditional execution of code. It is used to check a condition and execute a block of code if the condition is true, and another block of code if the condition is false.
Here is the basic syntax of the if else
statement in C++:
if (condition) { // code to execute if condition is true } else { // code to execute if condition is false }
In the above syntax, condition
is an expression that evaluates to a Boolean value (i.e., true
or false
). If condition
is true, the code inside the first block (i.e., the code between the opening curly brace {
and the closing curly brace }
) will be executed. If condition
is false, the code inside the second block (i.e., the code after the else
keyword) will be executed.
Here is an example of how to use the if else
statement in C++:
#include <iostream> using namespace std; int main() { int age; cout << "Enter your age: "; cin >> age; if (age >= 18) { cout << "You are an adult." << endl; } else { cout << "You are not an adult." << endl; } return 0; }
In this example, the program prompts the user to enter their age, and then uses an if else
statement to check whether the age is greater than or equal to 18. If it is, the program prints “You are an adult.” If it is not, the program prints “You are not an adult.”
I hope this helps you understand the if else
statement in C++! Let me know if you have any questions.