The if-else statement in C++ is a control flow structure used to execute code conditionally. It allows you to check a boolean condition (an expression that evaluates to true or false) and execute different blocks of code depending on whether the condition is true or false.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
Example:
#include <iostream>
using namespace std;
int main() {
int age = 15;
// Checking if the person is eligible to vote
if (age >= 18)
{
cout <<"You are eligible to vote."<< endl;
} else {
cout <<"You are not eligible to vote."<< endl;
}
return 0;
}
Output:
You are not eligible to vote.
Example: If number is not positive
#include <iostream>
using namespace std;
int main() {
int number = -20;
// Checking if the number is positive
if (number > 0)
{
cout <<"Number is positive"<< endl;
} else {
cout <<"Number is not positive"<< endl;
}
return 0;
}
Explanation:
- Condition: number >= 0 is the condition being checked.
- Since number is less than 0, then condition evaluates to false.
Output:
Number is not positive