Conditional Statements
- C++ has the following conditional statements:
if, else, else if, switch
- We use Relational operators for conditions :
<, <=, >, >=, ==, !=
- We can have multiple conditions using Logical operators :
&&, ||AND, OR
if Statement
- The
ifstatement is used to execute a block of code only if the specified condition is true.
if-else Statement
- The
if-elsestatement allows you to specify two blocks of code. - One to be executed if the condition is true and another to be executed if the condition is false.
if-else if-else Statement
- The `if-else if-else`` statement allows you to check multiple conditions.
- And execute the corresponding block of code for the first true condition.
Simple Example of Conditional Statement
// conditional_statements.cpp
int num;
cout << "Enter a Number : ";
cin >> num;
if (num > 0) {
cout << "Number is positive." << endl;
} else if (num < 0) {
cout << "Number is negative." << endl;
} else {
cout << "Number is zero." << endl;
}
Short Hand If...Else (Ternary Operator)
- Used to replace multiple lines of code with a single line.
- It is often used to replace simple if else statements
- Syntax :
variable = (condition) ? expressionTrue : expressionFalse;
Dynamic Declaration
- If a variable is declared in a block, it's memory will be deleted after the program come out from the block.
- It's memory limited to that block only.
Switch Statements
- Switch statement is another way to handle multiple cases or conditions.
- Useful when we have a variable that can take on different values, and we want to perform different actions based on the value of that variable.
- The
breakstatement is used to exit the switch statement after a case is matched. - If no match is found, the code under the
defaultlabel (if present) is executed. - Only integral type data is allowed in case statement.
charandintare integral type data. -
Fall-thru means executing next case also. (Happens when there is no
breakafter case).// switch_statement.cpp char grade; cout << "Enter your grade (A, B, C, D, or F): "; cin >> grade; switch (grade) { case 'A': cout << "Excellent!\n"; break; case 'B': cout << "Good job!\n"; break; case 'C': cout << "Satisfactory.\n"; break; case 'D': cout << "Needs improvement.\n"; break; case 'F': cout << "Fail.\n"; break; default: cout << "Invalid grade entered.\n"; }
Short-Circuiting
- Behavior of logical operators (like
&&and||) where the evaluation of the second operand is skipped if the result can be determined by the value of the first operand alone. -
This can be especially useful in conditional statements.
Logical AND (&&) :
- If the left operand of
&&is false, the right operand is not evaluated because the overall result will be false regardless of the value of the right operand.
Logical OR (||) :
- If the left operand of
||is true, the right operand is not evaluated because the overall result will be true regardless of the value of the right operand.
- If the left operand of