Questions on Section 12 - The switch statement

Calendar

Question 1

Write a program that gets the user to enter a number in the range 1 to 12, representing a month of the year. The program then displays the number of days in that month. You will have to decide for yourself what to do about February. Adapt the program so that it prints the name of the month as well.

Question 2

This simple program contains a switch statement (and little else!). I have deliberately missed the break statements from each case clause.

#include <iostream.h>
void main ()
  { int x;
    cin >> x;
    switch (x)
     { case 1 : cout << "x is 1";
       case 2 : cout << "x is 2";
       case 3 : cout << "x is 3";
       default : cout << "x is something else";
     }
  }

What effect does missing the break statements have? Try running the program and entering differing values of x to see.

Question 3

Take a look at Worked Example 3, which will tell you how to solve this one.

Combination safe I have a safe in my office with three dials and red button. The numbers on the dials go from 1 to 4. You open the safe by setting the numbers on the dials and then pressing the button.

The safe will open if the digits on the dial add up to 7. If the sum of the digits is equal to 4, then the safe blows up, destroying the thief and its own contents. If any of the digits is a 3, then the computer chip inside the safe automatically calls Security and informs them that the safe has been opened. Any other combination causes the safe to sound the alarm and summon the police.

How would you implement all this in a computer program which mimics the safe?

Question 4

Here is a fruit machine. There are three dials, each of which has a lemon, a cherry, a bell and an orange. Prizes are awarded as follows:

Combination
Prize
OrangeOrangeOrange 10p
BellBellBell 25p
LemonLemonLemon 60p
CherryCherryCherry £1.00
CherryOrangeBell 40p
LemonBellBell 45p

Fruit machine Although you don't yet have the knowledge to get the computer to pick random numbers, you can write the part that takes the values on the wheels and displays what prize if any the user has won. I will let you decide exactly how to set this out, although it would be useful to use a switch statement. To get the values on the wheels, I suggest you get the user to type them in. At some point, in a later section, you will learn how to produce random numbers in a program.


Go back Go back to the tutorial