ITP 165 Lecture 4: More Conditionals_ Nested Conditionals_ Switch Statements

30 views1 pages
ITP 165: Intro to C++ - Lecture 4: More Conditionals; Nested Conditionals; Switch
Statements
Else-if expressions
else if must always occur immediately after an if or an else if
An else if does not necessarily need to be followed by an else
You can have any number of else ifs in succession
If you have an else, it must be after all of the else ifs
Else-if statements imply mutual exclusivity
Only ONE of the statements will execute
Nesting Statements
Since an if statement is a type of statement, we can nest them
In many cases, nested ifs can be equivalent to if-else if-else chains
Switch statements
● syntax:
switch (select) {
case 1:
// Option 1
break;
default:
// Invalid option
break;
default case - what’s executed if the variable was not equal to any of the other cases
Switch only works in the instance where the condition is that the value equals a specific
number
switch only works on whole numbers
If you need complex behavior like “greater than 0 but less than 100” you need to use
if/else if statements
Don’t forget the break after every case
Keep case-related calculations and statements inside each case
Keep generic-case related calculations and statements outside of the switch
Conditionals
If you want to satisfy two conditions at once, you can combine the conditions using a
Boolean operator
Don’t always rely on the order of operations to sort out which evaluation to do first
Always make your conditionals explicitly clear
Unlock document

This preview shows half of the first page of the document.
Unlock all 1 pages and 3 million more documents.

Already have an account? Log in

Document Summary

Itp 165: intro to c++ - lecture 4: more conditionals; nested conditionals; switch. Else if must always occur immediately after an if or an else if. An else if does not necessarily need to be followed by an else. You can have any number of else ifs in succession. If you have an else, it must be after all of the else ifs. Only one of the statements will execute. Since an if statement is a type of statement, we can nest them. In many cases, nested ifs can be equivalent to if-else if-else chains. Default case - what"s executed if the variable was not equal to any of the other cases. Switch only works in the instance where the condition is that the value equals a specific number. If you need complex behavior like greater than 0 but less than 100 you need to use if/else if statements. Don"t forget the break after every case.

Get access

Grade+
$10 USD/m
Billed $120 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers