Table of Contents
Overview:
- Terms to know: Condition
- New code: How to write if statements, if/else statements, if/else if statements
Branching is one of the core forms of controlling the flow of the program. We ask a question, and based on the result we perhaps do this code over here or maybe that code over there - the program results change based on variables and data accessible to it. We will mostly be using if / else if / else statements, though switch statements have their own use as well. Make sure to get a good understanding of how each type of branching mechanism "flows".
1. Yes or no? - If/Else statements
The computer only understands "yes/no" questions - questions that either result in true or false. Based on these outcomes, we can choose to execute one set of code or another.
Form of an if/else statement:
// Do things 1
if ( CONDITION )
{
// Do things 2-a
}
else
{
// Do things 2-b
}
// Do things 3
The else block is executed when the if check fails. If the CONDITION is false, we can use DeMorgan's Laws to figure out what the program's state is during the else.
NOTE: The else statement NEVER has a CONDITION.
Example C++ source: Displaying "can't vote" if age is less than 18, or "can vote" otherwise
cout << "Enter your age: "; cin >> age; if ( age < 18 ) { result = "can't vote"; } else { result = "can vote"; } cout << "Result: " << result << endl;
If the age is less than 18, it will set the result variable to
"can't vote". If that boolean expression is false, that means
age is \(\geq\) 18, and then it will set the result to "can vote".
Finally, either way, it will display "Result: " with the value of
the result variable.
Review 1. Given the if statement:
if ( studentCount <= maxStudents ) { cout << "You can register for the course!" << endl; } else { cout << "Course is full!" << endl; }
When is "You can register for the course!" displayed and when is "Course is full!" displayed?
2. Standalone If statement
For a basic if statement, we use the syntax:
// Do things 1
if ( CONDITION )
{
// Do things 2-a
}
// Do things 3
The CONDITION will be some boolean expression. If the boolean
expression result is true, then any code within this if statement's
code block (what's between { and }) will get executed. If the
result of the expression is false, then the entire if statement's
code block is skipped and the program continues.
Example: C++ source: Displaying "(OVERDRAWN!)" only if the bank balance is less than 0
cout << "Bank balance: " << balance; if ( balance < 0 ) { cout << " (OVERDRAWN!)"; } cout << " in account #" << accountNumber << endl;
Program output: Output with balance = -50
Bank balance: -50 (OVERDRAWN!) in account #1234
Program output: Output with balance = 100
Bank balance: 100 in account #1234
- The special message "OVERDRAWN!" only gets displayed when the balance is less than 0.
- The following
coutthat gives the account number is displayed in all cases.
Review 2. Given the if statement:
cout << "Bank balance: $" << balance; if ( balance < 0 ) { cout << " (OVERDRAWN)" << endl; }
When would "Bank balance" be shown to the screen without (OVERDRAWN), and when would the bank balance and overdrawn text be shown?
3. If/Else if/Else statements
In some cases, there will be multiple scenarios we want to search for, each with their own logic. We can add as many else if statements as we want - there must be a starting if statement, and each else if statement will have a condition as well.
We can also end with a final else statement as a catch-all: if none of the previous if / else if statements are true, then else gets executed instead. However, the else is not required.
Form of an if/else if/else statement
// Do things 1
if ( CONDITION1 )
{
// Do things 2-a
}
else if ( CONDITION2 )
{
// Do things 2-b
}
else if ( CONDITION3 )
{
// Do things 2-c
}
else
{
// Do things 2-d
}
// Do things 3
Example: Displays a letter grade based on range, 90 and above is an 'A', and so on…
cout << "Enter grade: "; cin >> grade; if ( grade >= 90 ) { letterGrade = 'A'; } else if ( grade >= 80 ) { letterGrade = 'B'; } else if ( grade >= 70 ) { letterGrade = 'C'; } else if ( grade >= 60 ) { letterGrade = 'D'; } else { letterGrade = 'F'; } cout << "Grade: " << letterGrade << endl;
- I'm first checking if the grade is 90 or above. If it is, then
I know the letter grade is
'A'. - However, if it's false, it will go on and check the next else if statement. At this point, I know that since grade >= 90 was FALSE
- that means: grade < 90 is TRUE.
- Since the next statement checks if grade >= 80
- if this one is TRUE, I know that: grade < 90 AND grade >= 80
Review 3. Given the if statement:
if ( grade >= 90 ) { cout << "Grade: A" << endl; } else if ( grade >= 80 ) { cout << "Grade: B" << endl; } else if ( grade >= 70 ) { cout << "Grade: C" << endl; } else { cout << "You need to retake the course" << endl; }
- When is "Grade: A" displayed?
- When is "Grade: B" displayed?
- When is "Grade: C" displayed?
- When is "You need to retake the course" displayed?
4. Nesting if statements
If statements, While loops, and For loops all have code blocks:
They contain internal code, denoted by the opening and closing curly
braces { }. Within any block of code you can continue adding code.
You can add if statements in if statements in if statements, or loops
in loops in loops.
Nesting an if statement within another if statement basically gives you a boolean expression with an AND.
Example:
if ( wantsToVote ) { if ( age >= 18 ) { AllowToVote(); } }
Equivalent logic:
if ( wantsToVote && age >= 18 ) { AllowToVote(); }
Whether you implement some logic with nested if statements, or with if / else if statements using AND operations is a matter of design preference- in some cases, one might be cleaner than the other, but not always.
If you have a statement like this:
if ( conditionA )
{
if ( conditionB )
{
Operation1();
}
else
{
Operation2();
}
}
It could be equivalently described like this:
if ( conditionA && conditionB )
{
Operation1();
}
else if ( conditionA && !conditionB )
{
Operation2();
}
Review 4. Given this code snippet:
if ( computerOn == true ) { if ( printerOn == true ) { cout << "RESULT A" << endl; } else { cout << "RESULT B" << endl; } } else { if ( printerOn == true ) { cout << "RESULT C" << endl; } else { cout << "RESULT D" << endl; } }
When is each result displayed?
5. Logic operators with if statements
We can also combine multiple conditions together using our logic operators:
- AND:
&& - OR:
|| - NOT:
!
If we have an if statement with two conditions combined with an AND, then the if statement is only executed if all sub-conditions are true:
if ( CONDITION1 && CONDITION2 )
DoThingOne(); /* All conditions were true */
else
DoThingTwo(); /* One or more conditions were false */
If we have an if statement with two conditions combined with an OR, then the if statement is executed if at least one sub-condition is true:
if ( CONDITION1 || CONDITION2 )
DoThingOne(); /* One or more conditions were true */
else
DoThingTwo();/* All conditions were false */
Review 5. Given this code snippet:
if ( choice < 1 || choice > 5 ) { cout << "INVALID INPUT!" << endl; } else { cout << "Valid input" << endl; }
When would "INVALID INPUT!" be displayed, and when would "Valid input" be displayed?
Review 6. Given this code snippet:
if ( choice >= 1 && choice <= 5 ) { cout << "Valid input" << endl; } else { cout << "INVALID INPUT!" << endl; }
When would "Valid input" be displayed, and when would "INVALID INPUT!" be displayed?