In C++ an if-else statement controls conditional branching. Statements in the if-branch are executed only if the condition evaluates to a non-zero value (or true ). If the value of condition is nonzero, the following statement gets executed, and the statement following the optional else gets skipped.
If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript’s “Conditional” Statements, which are used to perform different actions based on different conditions.
Syntax:
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.
For Example:
#include <iostream>
using namespace std;
int main()
{
int age;
cout<<"Enter your age"<<endl;
cin>>age;
if (age>150 || age<1){
cout<<"Invalid age"<<endl;
}
else if (age>=18)
{
cout<<"You can vote"<<endl;
}
else{
cout<<"You can't vote"<<endl;
}
}
1 Comment
[…] some programming languages, like c++ function overloading or method overloading is the ability to create multiple functions of the same […]