CIS 150 Selection

Objectives

  • solve problems using C++ selection
  • use C++ if statements
  • use C++ if/else statements
  • use C++ nested if/else statements
  • use the C++ conditional operator (if time permits)
  • use C++ switch statements (if time permits)
  • validate user input (very basic validation)

Selection

Remember that these topics are covered well in the text. These notes are just an outline for classroom discussion/lecture.

  • if statement - used for single-branched selection if (condition) { statement(s) // executed if condition is true }
  • if/else - used for two-branched selection if (condition) { statement(s) // executed if condition is true } else { statement(s) // executed if condition is false }
  • nested if/else - used for complex selection if (condition1) { statement(s) // executed if condition1 is true if (condition2) { statement(s) // executed if condition1 AND condition2 are true } else { statement(s) // executed if condition1 is true but condition2 is false } } else { statement(s) // executed if condition1 is false }
  • switch switch (intExpression) { case value1: statement(s) // executed if intExpression == value1 break; case value2: statement(s) // executed if intExpression == value2 break; default: statement(s) // executed if no values matched intExpression }
  • conditional operator (?:)
  • see testsel1.cpp for "if" demonstration
  • see testsel2.cpp for "if/else" demonstration
  • see testsel3.cpp for "if/else" range checking
  • see testsel4.cpp for "switch" demonstration
  • see testsel5.cpp for "?:" demonstration, calculates maximum value

Sample of nested "if"

if (eligibleForOvertime) { if (hoursWorked > 40) { grossPay = hoursWorked * rate + (hoursWorked-40) * rate/2; } else { grossPay = hoursWorked * rate; } }

Sample of conditional operator

  • only ternary operator
  • operates like an inline if/else
  • expr1 ? expr2 : expr3
    if expr1 is true, the whole thing is replaced by expr2,
    otherwise it is replaced by expr3
  • grossPay = hours>40 ? rate*40 + (hours-40)*rate*1.5 : hours*rate;

Sample of multi-branch selection (switch)

  • allows branching based on equality to integral values
  • less flexible then if/else, but useful for certain situations which have a very limited number of input values (such as menu selections)
  • if statements easily handle ranges of values (such as hours > 40, or age > 21 && age < 40), but switch statements do not
  • switch (option) { case 1: cout << "Loading from file\n"; break; case 2: cout << "Saving to file\n"; break; case 3: cout << "Printing report\n"; break; case 4: cout << "Terminating program\n"; break; default: cout << "Invalid choice\n"; }

Validating user input

  • data validation makes use of the selection structures we have just covered
  • see testio2.cpp for data validation using if/else
  • see testio3.cpp for data validation using switch

More examples