Conditional statements in C++ (1)
Course: C++ Part 1 - chapter 5
C++ like Javascript has the following conditional statements:
- if else
- switch
- conditional operator
If Else statements
Section titled “If Else statements”if (condition_1) { // Executed if condition_1 is true} else if (condition_2) { // Executed if condition_1 is false and condition_2 is true} else { // Executed if both condition_1 and condition_2 are false}We can even have nested if else statements or just single if statement
// Only if statementif (condition) {}
// Nested if elseif (condition_outer) { if (condition_inner) {} else {}} else {}Switch statements
Section titled “Switch statements”switch(variable) { case 1: // When variable is 1 break; case 2: // When variable is 2 break; default: // When none of the case statements is satisfied}💡 The case value must be of type integer or character
💡 Like Javascript, default statement is optional. Also break keywords are optional.
Conditional operators
Section titled “Conditional operators”condition ? true_statement : false_statementExamples:
bool is_even = (n % 2 == 0) ? true : false;
int absolute_diff = (a > b) ? a - b : b - a;