Computer Programming for Homeschool Students and Other Beginners

Sequence, Selection and Loop Structures

Learn about structured programming, the sequence structure, the selection structure, and the loop structure.  Then learn how to write a Scratch program that illustrates the selection structure, mouse events, and Cartesian coordinates.  Finally write a student project that demonstrates your understanding of the concepts learned with the first program.

Published:  May 3, 2008
Last Revised: May 16, 2008
By Richard G. Baldwin

Homeschool Programming Notes # 104


 

Preface

General

This is the third lesson in a series that is designed specifically for teaching computer programming to homeschool students and their parents, but everyone is welcome to use the lessons in this series.

I will begin by helping you to learn about structured programming, the sequence structure, the selection structure, and the loop structure.  Then I will show you how to write a Scratch program that illustrates the selection structure, mouse events, and Cartesian coordinates.  (I will illustrate the loop structure in a future lesson.)

Finally I will provide the specifications for a program for you to write in order to demonstrate your understanding of the concepts learned from the first program.

Viewing tip

I recommend that you open another copy of this lesson in a separate browser window and use the following links to easily find and view the figures while you are reading about them.

Figures

Supplementary material

I recommend that you also study the other lessons in my extensive collection of online programming tutorials.  You will find a consolidated index at www.DickBaldwin.com.

General background information

In this lesson, I will help you learn about:

In introductory programming courses, you will often hear a lot about something called structured programming.  While I don't claim to be an expert in that area, in comparison with more modern and complex programming concepts such as runtime polymorphism, structured programming seems to be fairly mundane.

However, that's not to say that structured programming isn't important.  It is very important.  But it is just a small bump in the road of learning that leads to an understanding of object-oriented programming.

So, what is structured programming?

Basically, the concept of structured programming says that any programming logic problem can be solved using an appropriate combination of only three programming structures, none of which are complicated.  The three structures are known generally as:

One door in and one door out

To understand structured programming, you need to think in terms of a section of program code that has only one entry point and one exit point.  It is very important that there cannot be multiple entry points or multiple exit points. 

There must be only one way into the section of code and one way out of the section of code.

Nesting of structures is allowed

Another important part of the concept is that structures may be nested inside of other structures provided that every structure meets the basic rules for a structure.

Thus, by nesting simple structures inside of simple structures, large and complex overall structures can be constructed.

The sequence structure

You saw the sequence structure in an earlier lesson.  Basically we can describe the sequence structure using the pseudocode shown in Figure 1.

Figure 1. The sequence structure in pseudocode.
Enter
  Perform one or more actions in sequence
Exit

Thus, the general requirement for the sequence structure is that one or more actions may be performed in sequence after entry and before exit.

There may not be any branches or loops between the entry and the exit.

All actions must be taken in sequence.

The action elements themselves may be structures

However, it is important to note that one or more of the action elements may themselves be sequence, selection, or loop structures.

If each of the structures that make up the sequence has only one entry point and one exit point, each such structure can be viewed as a single action element in a sequence of actions.

The sequence structure is the simplest of the three, and I don't know much more that I can say about it.

The selection structure

The selection or decision structure can be described as shown in the pseudocode in Figure 2.

Figure 2. The selection structure in pseudocode.
Enter
  Test a condition for true or false
  On true 
    Take one or more actions in sequence
  On false
    Take none, one, or more actions in sequence
Exit

Test a condition for true or false

Once again, there is only one entry point and one exit point.

The first thing that happens following entry is that some condition is tested for true or false.

If the condition is true, one or more actions are taken in sequence and control exits the structure.

If the condition is false, none, one or more different actions are taken in sequence and control exits the structure.  (Note the inclusion of the word none here.)

The action elements may themselves be structures

Once again, each of the action elements in the sequence may be another sequence, selection, or loop structure.

Eventually all of the actions for a chosen branch will be completed in sequence and control will exit the structure.

Sometimes no action is required on false

It is often the case that no action is required when the test returns false.  In that case, control simply exits the structure without performing any actions.

The loop structure

The loop or iteration structure can be described as shown in the pseudocode in Figure 3.

Figure 3. The loop structure in pseudocode.
Enter
  Test a condition for true or false
  Exit on false
  On true
    Perform one or more actions in sequence.
    Go back and test the condition again

As before, there is only one entry point and one exit point.  Note that in this case, the exit point is not at the end of the pseudocode.  Instead, it follows the test.

Perform the test and exit on false

The first thing that happens following entry is that a condition is tested for true or false.

If the test returns false, control simply exits the structure without taking any action at all.

Perform some actions and repeat the test on true

If the test returns true:

During each iteration, if the test returns false, control exits the structure.  If the test returns true, the entire process is repeated.

Each action element may be another structure

Each of the action elements may be implemented by another sequence, selection, or loop structure.

Eventually all of the actions will be completed and the condition will be tested again.

Need to avoid infinite loops

Generally speaking, unless something is done in one of the actions to cause the test to eventually return false, control will never exit the loop.

In this case, the program will be caught in what is commonly referred to as an infinite loop.

Other possible structures

In some programming languages, there are a couple of structures other than sequence, selection, and loop that structured-programming experts are willing to accept for convenience:

These structures are not required for the solution of programming logic problems.  Also, they are not supported by either Scratch or Alice 2.0, so you won't learn about them until we get to Java.

Preview

In this lesson, I will present and explain the simplest example of a selection structure that I was able to write in Scratch without using variables and without using relational or logical operators.  (I will explain operators, including relational and logical operators in future lessons.)

Screen output for the program named IfSimple01

The program places a basketball and two beach balls on the Stage as shown in Figure 4.

Figure 4. User interface for the program named IfSimple01.

Click the green flag or the basketball

When the user clicks the green flag in the upper right corner, the three balls are placed in a horizontal line with the basketball in the center.

Scratch code, which can be paraphrased as shown in Figure 5, is executed each time the user clicks the basketball with the mouse.

Figure 5. A paraphrased version of the Scratch code.
when Basketball is clicked{
  move forward by 90 steps
  if(Basketball is touching RightBeachball){
  turn Basketball by 180 degrees
  }//end if
  if(Basketball is touching LeftBeachball){
    turn Basketball by 180 degrees
  }//end if
}

In other words, if you repetitively click the basketball with the mouse, it will move back and forth from left to right bouncing off of the two beach balls.  The basketball will keep bouncing back and forth between the two beach balls for as long as you continue clicking on the basketball.

Discussion and sample code

Developing the program

Let's walk through the steps required to develop this program.  I will deal first with the code that defines the behavior of the program when the user clicks the green flag in the upper right corner of Figure 4.

The Cartesian coordinate system
The position of sprites on the Stage in the Scratch user interface is based on a two-dimensional Cartesian coordinate system  (see Resources) with the origin at the center of the Stage.

Three sprites

Note in the lower right corner of Figure 4 that this program contains two beach balls and one basketball in addition to the Stage.

You add sprites to your program by clicking on the button with the icon of the file folder in the gray area immediately below the white Stage area in Figure 4.

When you click on one of the sprites that you have added to the program, that sprite appears at the top of the center pane.  Having done that, you can then drag certain blocks into the center pane that define the behavior of that sprite.

Program code for the LeftBeachball

The code that I wrote for the sprite named LeftBeachball is shown in Figure 6.

Figure 6. Program code for the left beach ball

You are already familiar with the tan block shown in Figure 6 because you learned about it in the previous lesson (see Resources).  However, the blue block in Figure 6 has not been used prior to this lesson.

Adding the blue go to block to the program

The blue block shown in Figure 6 was added to the program module by:

Coordinate values
If you move the mouse pointer around in the user interface, the coordinates of the mouse pointer are displayed at the right end of the gray area immediately below the Stage as shown in Figure 4.  The x coordinates range from -240 at the left to +240 at the right.  The y coordinates range from +180 at the top to -180 at the bottom.

Behavior of the LeftBeachball

The behavior of the program module shown in Figure 6 can be interpreted as follows:  When the user clicks the green flag, cause the sprite named LeftBeachball to move to a location with an x (horizontal) coordinate value of -200 and a y (vertical) coordinate value of 0.  Since the origin is at the center of the Stage, this causes the beach ball to move to the left of the origin on the horizontal axis.

Some experimentation was required

Because I didn't know the diameter of the beach ball, I had to experiment to determine how far to move it to the left of the origin to locate it at the left side of the Stage as shown in Figure 4.  I settled on a value of -200 for the x coordinate and a value of 0 for the y coordinate.

Positioning the other beach ball

In the interest of brevity, I won't show the code required to position the other beach ball, but I did exactly the same thing for the other beach ball except that I specified the value of the x coordinate to be 200 instead of - 200.  This causes the beach ball named RightBeachball to move to the right side of the Stage when the user clicks the green flag.

Initializing the position of the basketball

Figure 7 shows a portion of the center pane after clicking on the sprite named Basketball.

Figure 7. Initializing the position and orientation of the basketball.

You will note that the tan block and the uppermost blue block in Figure 7 is the same as in Figure 6 except that the x coordinate value is set to 0.  This causes the basketball to move to the origin when the user clicks the green flag.

Initializing the orientation of the basketball

However, Figure 7 contains a block that is not contained in Figure 6.  The bottom blue block in Figure 7 is used to set the orientation of the basketball.  (By orientation, I mean the direction that the basketball is facing.)

It may seem strange to say that a round basketball is facing in one direction or the other.  However, every sprite has a front, back, top, and bottom even in those cases where it is not visually obvious.  (The orientation would be visually obvious if I were to use an animal for the sprite in place of the basketball.)

After you drag the blue block labeled point in direction into the center pane, you can click the arrow in the white box to expose the following four choices:

As you can see, I chose the choice that causes the basketball to face to the right.  As a result, when the user clicks the green flag, the basketball will move to the origin and turn to face the right.

Handling mouse events on the basketball

Figure 8 shows all of the code that applies to the basketball.

Figure 8. All of the code that applies to the basketball.

The top script in Figure 8 is simply another image of the script that was shown in Figure 7.  At this point, we are interested in the behavior of the bottom script in Figure 8.

Behavior of the bottom script

The tan block labeled when Basketball clicked specifies that all of the actions produced by the blocks below that block will occur when the user clicks the basketball with the mouse.  Furthermore, those actions will occur in top to bottom order.

The blue block labeled move 90 steps causes the basketball to move 90 steps forward.  Each step constitutes one unit in the Cartesian coordinate system.  For example, if you were to change this value from 90 to 240, that would cause the basketball to move from the origin to the extreme right edge of the Stage.

The selection block

As I indicated earlier, the selection structure is sometimes referred to as a decision structure.  In other words, this structure causes the program to select or make a decision between two alternatives.  The pseudocode in Figure 9 describes this process.

Figure 9. Pseudocode for a selection structure.
if a specified condition is true
 perform a specified action
otherwise (when the specified condition is not true)
 perform a different action

Sometimes the second part of the selection process isn't needed.  In other words, in some cases, if the specified condition is not true, there is no requirement to do anything at all.  That is the case in this program.

Two independent decisions

This program makes two independent decisions shown by the pseudocode in Figure 10.

Figure 10. Two independent decisions.
if the basketball is touching the beach ball on the right
 turn around and face to the left

if the basketball is touching the beach ball on the left
 turn around and face to the right

These two decisions are implemented by the two tan blocks in Figure 8 containing the word if.

The Control group
Clicking the tan Control button shown at the upper left in Figure 4 exposes more than fifteen programming blocks, but only two of them are used to create selection structures.

Selection control structures available in Scratch

Clicking the tan Control button shown at the upper left in Figure 4 exposes the two blocks shown in Figure 11.  These two blocks can be used to create selection structures.  Selection structures are created by dragging these two blocks into the center pane in order to apply them to a particular sprite.

Figure 11. Selection control structures available in Scratch.

How do the two blocks differ?

The bottom block in Figure 11 is used to select between two specific actions.  The top block is used when there is only one action and you need to decide whether to take that action or not.  That is the case in this program.  If the basketball is touching a beach ball, a specific action is required.  If the basketball is not touching a beach ball, no specific action is required.

Specifying the condition on which the decision will be based

Note the empty depressed area in each of the blocks shown in Figure 11 (the rectangle with the pointed ends).  In order to use either of these blocks, you must drop another block having the same shape into the depressed area.  The block that you drop into that area must specify the condition that will be used to make the decision.

Two groups of programming blocks have the correct shape

Unless I missed seeing some others, there are only two buttons at the top left of Figure 4 that expose blocks having the required shape:

In this case, we will select and use a block from the light blue Sensing group.  (We will use programming blocks from the green Numbers group in a future lesson.)  All of the blocks belonging to the Sensing group are shown in Figure 12.

Figure 12. Programming blocks belonging to the Sensing group.

Will use the touching block

We will use the block labeled touching followed by a pull-down list and a question mark.  The items that appear in the pull-down list depend on the sprites that have been added to the program when you examine the list and the sprite that has been selected for programming in the center panel.  For this program, that list consists of the following choices when the basketball has been selected for programming:

The top two choices are always there.  The remaining choices depend on the sprites that have been added to the program at the point in time when you pull down the list and the sprite that has been selected for programming.  (Note that the Basketball sprite does not appear in the above list because it was selected for programming when I examined the list.)

Go back and examine the script

Getting back to the bottom script in Figure 8, you can see that I dragged two copies of the top if block shown in Figure 11 into the center panel and connected the blocks as shown in Figure 8.  Then I dragged two copies of the touching block from the Sensing group shown in Figure 12, and dropped each of those blocks into the corresponding locations in the if blocks in Figure 8.

Then I selected RightBeachball from the pull-down list for one of the touching blocks and selected LeftBeachball from the pull-down list for the other touching block.

Conditions have been established - need actions

At this point, I had the conditions for the two selection structures established, but I hadn't yet specified the actions to be taken when one or the other of the conditions is found to be true.  That is the next thing on the agenda.

Programming blocks belonging to the Motion group

Figure 13 shows the programming blocks that are exposed by clicking the Motion button at the top left of Figure 4.

Figure 13. Programming blocks belonging to the Motion group.

You saw three of the blocks from Figure 13 being used in Figure 6, Figure 7, and immediately below the top tan block in the bottom script in Figure 8.  Now we need to use another of the blocks from Figure 13.

Turn around and face the other way

Recall that the blue point in direction block in the top script in Figure 8 causes the basketball to turn to face to the right when the user clicks the green flag.

The two turn blocks in the bottom script in Figure 8 cause the basketball to rotate around its center by 180 degrees.  This, in turn, causes it to face in the opposite direction from the direction that it was previously facing.  (It also turns it upside down, but that doesn't matter for a round basketball.)  This is the action that is required whenever either of the touching blocks is true.  In other words, whenever the basketball touches either of the beach balls, it must turn to face the opposite direction and be prepared to move 90 steps in that direction the next time the user clicks the basketball.

An online version of this program is available

A copy of this program has been posted online for your review (see Resources for the URL).  If you don't find the program using that URL, search the Scratch site for the user named dbal.

Run the program

I encourage you to use the information provided above to write this program.  Experiment with the code, making changes, and observing the results of your changes.  Make certain that you can explain why your changes behave as they do.

Just for fun, use blocks from the purple Sound group and add some sound effects to your program.

I also encourage you to write the program described below.

Student programming project

Write a Scratch program named IfWithVar01 that produces the output shown in Figure 14 when the user clicks the green flag.

Figure 14. Initial output from the program named IfWithVar01.

Orthogonal axes in Cartesian coordinates

When the user clicks the green flag, a DrawingPencil sprite draws a pair of orthogonal axes that intersect at the origin in the white Stage area.  Make the horizontal axis extend from -200 to 200.  Make the vertical axis extend from -100 to 100.

Draw a straight line to the location of the next mouse click

Each time the user clicks the mouse in the white Stage area (after the user has clicked the green flag), a straight line is drawn from the current location of the DrawingPencil to the location where the mouse click occurred.  Figure 15 shows an example output after two mouse clicks.

Figure 15. Program output after having clicked twice in the Stage area.

A sneak peek at the back of the book

In case you need to sneak a peek at the answer in the back of the book, a copy of this program has been posted online for your review (see Resources for the URL).  If you don't find the program using that URL, search the Scratch site for the user named dbal.

Summary

I began by explaining structured programming, the sequence structure, the selection structure, and the loop structure.  Then I presented and explained a Scratch program that illustrates the selection structure.  (The sequence structure is so simple that it doesn't require an explanation.  The loop structure will be explained in a future lesson.)  The program also illustrates the handling of mouse events and Cartesian coordinates.

Finally, I provided the specifications for a student-programming project for you to write to demonstrate your understanding of what you learned from the first program.

Copies of both programs have been posted online for your review (see Resources for the URL).  If you don't find the program using that URL, search the Scratch site for the user named dbal.

What's next?

In the next lesson, I will teach you about arithmetic operators.  In the two lessons following that one, I will teach you about relational and logical operators and how to use those operators to write the conditional expressions used in selection and loop structures.

Resources


Copyright

Copyright 2008, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP).  His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments.  (TI is still a world leader in DSP.)  In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com

-end-