Laboratory 3

Selection Structures

Introduction

In this lab we will learn to use the if statement to make decisions in a program. This will allow us to cause certain statements to be executed only when a given condition exists. Most of the examples in this lab involve the idea of putting a list of several numbers in order. In computer science this is called sorting. Although we will not attempt to sort more than four numbers, in Lab 12 we will learn how to sort lists of arbitrary length. Many of the routines presented here will become building blocks for more complex tasks later.

Key Concepts

Ø  Swapping values

Ø  1-way selection

Ø  2-way selection

Ø  Problem solving: Sorting

Before the Lab

Read Sections 4.1 – 4.6 in Cohoon and Davidson.

Preliminary

·  Turn the PC on, if necessary.

·  Access the network.

·  Copy the source files from the Lab 03 Source Files folder.

·  Start up CodeWarrior.

·  Open the LabWork project.


Two-Way Selection

Observation

·  Open the file Larger.cpp and add it to the LabWork project. (Remember, it is now understood that you should remove old source code.)

The purpose of this program is to read two numbers and to print the larger.

·  Compile the program and run it twice. The first time, enter the smaller value first; the second time, enter the larger value first.

When you enter two values, note that the larger one is always printed, whether it was entered first or second.

·  Look at the source code and be sure you understand how the program works.

The program “selects” exactly one of the two cout statements to be executed, based on the order of the input values, using if .. else. This is called two-way selection.

·  What is the difficulty of extending this to three values, i.e., a program that prints the largest of three integers?

Swapping Values

Observation

·  Add the program Swap.cpp to the LabWork project.

This program will read two integers and then swap their values. For example, if a is given the value 3 and b is given the value 4, then these will be swapped so that a has the value 4 and b has the value 3.

·  Run Swap.cpp.

Enter two values and see that they are swapped. We’ll see later how useful an operation this is!

·  Look at the source code and note that an extra object temp was required to accomplish the swap.

·  Why is this so? What is wrong with simply writing the following?

a = b;

b = a;

One-Way Selection

Observation

·  Add the file LargerSwap.cpp to the LabWork project.

This program has the same purpose as Larger.cpp, but it solves the problem differently. Note how a swap ensures that a’s value is the larger.

·  Compile the program and run it twice, as before, once with the larger value first and once with the smaller value first.

·  Look at the source code and be sure you understand how the program works.

Note that there is an if with no corresponding else, since no alternative action needs to be specified. This is an example of one-way selection.

·  Consider whether this idea can easily be extended to three values, i.e., a program that finds the largest of three integers by swapping.

Finding the Largest of Three Numbers

Observation

Suppose now we want to read three numbers and output the largest. The program Largest.cpp solves the problem in yet another way. An integer object max is introduced. As the list of integers is scanned, max is assigned the largest value seen so far.

·  Add the file Largest.cpp to the LabWork project.

·  Read the source code.

Note the object max, which is used to keep track of the largest value so far.

·  Trace the program (by hand) with a = 20, b = 30, c = 10 to understand how it works. What should happen?

·  Run the program.

·  Is the output correct?

Experimentation

·  Modify Largest.cpp so that it works for four values a, b, c, and d.

This program should read four integers and print the largest of them. Use the same method as in Largest.cpp; simply extend it from three integers to four integers.

·  Run Largest.cpp several times with different sets of input to be sure that it works.

Sorting Values

Observation

Suppose now we want to read three numbers and arrange them from largest to smallest. There are six permutations of the three numbers, only one of which is the desired order.

·  Add the program SortThree.cpp to the LabWork project.

·  Run SortThree.cpp a few times, with different permutations of the three numbers 10, 20, and 30. Is the output correct each time?

·  Trace the program with input 10 20 30 to understand how it works when it must perform all three swaps.

Experimentation

We will now make SortThree.cpp a little more efficient. Note that the third swap is possible only if the second swap took place. (Think about it!) If we know that the second swap did not take place, then there is no need to consider the third swap. To take advantage of this fact, we may “nest” the third if statement within the second if statement.

·  Select the lines of text

// NOTE: a may now be smaller than b

// Swap a and b if a is smaller

if (a < b) {

int temp = a;

a = b;

b = temp;

}

by clicking and dragging over them. It works best if you click in the left margin of the first line and then drag straight down until the last line is included. These lines should now be highlighted.

·  Cut the text. Do this by selecting Cut under the Edit menu, or by typing CTRL-X.

·  Click in the left margin of the line with the close curly brace } at the end of the second if statement.

·  Paste the text. Do this by selecting Paste under the Edit menu, or by typing CTRL-V.

For the sake of readability, we want to indent the pasted text one tab stop to the right, to indicate that it is nested within the other if statement. To do this,

·  Select the pasted text as you did before, by clicking and dragging.

·  Select Shift Right under the Edit menu, or type Command-].

·  Run the program several times.

·  Does it still work?

We now want to print the three numbers in ascending order, rather than descending order. We will leave this modification up to you. It is not hard.

·  Modify SortThree.cpp so that it prints the numbers in ascending order.

·  Change the output statement to read “ascending” instead of “descending.”

·  Run the program enough times to be sure that it works.

Finally, we will modify SortThree.cpp so that it sorts three names instead of three numbers.

·  Use Save As… under the File menu to save SortThree.cpp as SortNames.cpp.

·  Change the types of a, b, c, and temp from int to string.

·  Change the prompt so that it requests names.

·  Run SortNames.cpp entering three names instead of three numbers.

When you enter the names, enter each name as a single word. For example, you may enter John, but not John Doe.

·  Describe the output. What is special about the order of the names?

·  Run SortNames.cpp again. This time when you enter the names, let some of them begin with a capital letter and the rest begin with a lowercase letter.

·  What happens? Can you explain why?

Application

Open the MS Word document Lab 03 App.doc, found in the Lab 03 App subfolder, and follow the instructions.

Summary

Computer programs, such as those that sort numbers, need to make decisions “on the fly” about which statements are to be executed. They do so with the help of statements like C++’s if and else statements, among others. These are our first examples of C++ control structures, that is, statements which enable the program to control the flow of execution. In the next lab, we will investigate control structures that enable C++ programs to repeat a sequence of actions. This capability is at the heart of what makes computers so powerful.