C++ If/else statement 


If/else statements are an important concept in programming and are used to make decisions based on certain conditions.


 These statements allow the programmer to create branching logic in their code, allowing .

the program to take different paths depending on the input or current state of the program.

 In this article, we will explore the if/else statement in C++.


Syntax


The basic syntax of the if/else statement in C++ is as follows:


code


if (condition) { // code to be executed if the condition is true } else { // code to be executed if the condition is false } 


The condition is a Boolean expression that evaluates to either true or false.

 If the condition is true, the code in the first block is executed, and if it is false, the code in the second block is executed.


Example


Let's take a look at an example to see how the if/else statement works:


cCopy code


#include <iostream> int main() 

{ int age; 

std::cout << "Enter your age: "; 

std::cin >> age;

 if (age >= 18) { std::cout << "You are an adult." << std::endl; 

}

 else { std::cout << "You are a minor." << std::endl; } return 0; 


In this example, the program asks the user to enter their age. If the age is greater than or equal to 18, the program outputs "You are an adult.


" If the age is less than 18, the program outputs "You are a minor.

" The if/else statement is used to make this decision based on the value of the age variable.


Nested if/else statements


It is also possible to nest if/else statements inside one another to create more complex decision-making logic. For example:


cCopy code


#include <iostream> 

int main()

 { int age; std::cout << "Enter your age: "; std::cin >> age;

 if (age >= 18) { std::cout << "You are an adult." 

<< std::endl;

 } 

else 

{ i

f (age >= 13) { std::cout << "You are a teenager." << std::endl; 

else

 {

 std::cout << "You are a child." << std::endl; } } 

return 0;

 } 


In this example, if the user enters an age of 18 or older, the program outputs "You are an adult."

 If the age is less than 18, the program checks if the age is greater than or equal to 13. If it is, the program outputs "You are a teenager.

" If the age is less than 13, the program outputs "You are a child."


Logical operators


In addition to the basic if/else statement, C++ provides several logical operators that can be used to create more complex conditions. These operators include:


&& (logical AND)|| (logical OR)! (logical NOT)


The logical AND operator (&&) returns true if both of its operands are true. For example:


scss code


if (age >= 18 && age < 65) { // code to be executed if the age is between 18 and 64 } 


The logical OR operator (||) returns true if at least one of its operands is true. For example:


scssCopy code


if (age < 18 || age >= 65) { // code to be executed if the age is less than 18 or greater than or equal to 65 } 


The logical NOT operator (!) reverses the value of its