8.3 switch, break, and continue

 I l @ ve RuBoard

8.3 switch, break, and continue

The break statement has two uses. Used inside a switch , it causes the program to exit the switch statement. Inside a for or while loop, it causes a loop exit. The continue statement is valid only inside a loop and causes the program to go to the top of the loop.

To illustrate how these statements work, we've produced a new version of the calculator program. The new program prints the result only after valid data is input, and it has a help command.

The help command is special. We don't want to print the result after the help command, so instead of ending the help case with a break , we end it with a continue . The continue forces execution to go to the top of the loop.

When an unknown operator is entered, we print an error message. As with the help case , we use a continue statement to skip printing the result.

Finally, there is one special command: quit. This command is handled outside the switch . It is handled by the break at the top of the loop. Since the break is outside the switch, it belongs to the while loop and causes the program to exit the while .

The control flow for this program can be seen in Figure 8-2.

Figure 8-2. switch/continue
 I l @ ve RuBoard
 I l @ ve RuBoard

8.4 Programming Exercises

Exercise 8-1: Print a checkerboard (8-by-8 grid). Each square should be 5-by-3 characters wide. A 2-by-2 example follows :

```+-----+-----+

+-----+-----+

+-----+-----+
```

Exercise 8-2: The total resistance of n resistors in parallel is:

1 / R = 1 / R 1 + 1 / R 2 + 1 / R 3 + ... + 1 / R n

Suppose we have a network of two resistors with the values 400 and 200 . Our equation would be:

1 / R = 1 / R 1 + 1 / R 2

Substituting in the value of the resistors we get:

1 / R = 1 / 400 + 1 / 200

1 / R = 3 / 400

R = 400 / 3

So the total resistance of our two-resistor network is 133.3 .

Write a program to compute the total resistance for any number of parallel resistors.

Exercise 8-3: Write a program to average n numbers .

Exercise 8-4: Write a program to print out the multiplication table.

Exercise 8-5: Write a program that reads a character and prints out whether it is a vowel or a consonant.

Exercise 8-6: Write a program that converts numbers to words. Example: 895 results in "eight nine five."

Exercise 8-7: The number 85 is said "eighty-five," not "eight five." Modify the previous program to handle the numbers 0-100 so all numbers come out as we really say them. For example, 13 is "thirteen," and 100 is "one hundred."

 I l @ ve RuBoard
 I l @ ve RuBoard