Selection Flashcards
Three basic programming constructs
Sequence
Selection
Iteration
Sequence
ensures that commands are executes in the correct order
Selection
used in an algorithm to choose between two or more options
Uses if, else if, and else
When is if/else or else if used?
if/else is used if there are only two possible outcomes
it isn’t efficient to keep repeating them, as each separate if statement is checked after the selection has been made
if there are more than two outcomes, else if is used
this is more efficient, as after the correct condition is found, non of the other options are checked
When are else statements used?
used to state what should happen if none of the options in the if or else if statements are true
Nested if statements
If statements that are completely within another if statement
Every if statement needs it’s own endif statement
Switch/case
A programming construct that can also be used for selection
answer = input ("Please enter your choice") switch answer: case "A": print("That is incorrect") case "B": print("That is incorrect") case " C": print("That is correct") default: print("That is not recognised") endswitch
The default statement is used to trap errors in the same way as an else statement
A bowling alley gives a 5% reduction in price if there are four or more people on a lane and a further 10% reduction if they are members.
Write the code that will calculate the final charge. [5]
if numberOfPeople >= 4 then charge = charge - (charge/100*5) if membership == "Yes" then charge = charge - (charge/100*10) endif endif
print(“The charge is: “ + charge)
A shop gives a discount of 10% for purchase of £200 and over, up to a total discount of £300.
Wrote an algorithm, in pseudocode, that would allow a user to calculate the discount. [4]
charge = input("Please enter the money spent") if charge >= 200 then discount = charge/100*10 if discount > 300 then discount = 300 endif endif