If...Else
The conditional statement keywords:
Use if to execute the code block if the the condition is true
Use else to execute the code block, if the same condition is false
Use else if to execute a new condition to test, if the previous condition is false
What can the different conditions be?
Less than: a<b
Less than or equal to: a<=b
Greater than: a>b
Greater than or equal to: a>=b
Equal to a==b
Not Equal to: a!=b
The following is an if.. else example
Example:
#include <iostream>
using namespace std;
int main()
{
int age = 18;
if (age > 18) {
cout << "Eligible to Vote";
} else {
cout << "Not Eligible";
}
return 0;
}
The following is an else if..example
Example:
#include <iostream>
using namespace std;
int main()
{
int age = 18;
if (age < 18) {
cout << "Too young.";
} else if (age > 81) {
cout << "Too old.";
} else {
cout << "Just right.";
}
return 0;
}
Ternary Operator:
If only one condition/statement is to be executed the conditional operator(ternary operator) can be used instead.
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Left side of the semicolon will be executed if statement is true else if it is false right side will be executed.
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
int age = 20;
string result = (age < 18) ? "Too young" : "Eligible to Vote";
cout << result;
return 0;
}
Output:
Eligible to vote