Learn about structured programming, the sequence structure, the selection structure, the loop structure, and composite structures such as the multiple-choice structure.
Published: April 7, 2007
Last Updated: August 27, 2007
By Richard G. Baldwin
Alice Programming Notes # 165
This tutorial lesson is part of a series designed to teach you how to program using the Alice programming environment under the assumption that you have no prior programming knowledge or experience.
Have some fun
Because Alice is an interactive graphic 3D programming environment, it is not only useful for learning how to program, Alice makes learning to program fun. Therefore, you should be sure to explore the many possibilities for being creative provided by Alice while you are learning to program using these tutorials. And above all, have fun in the process of learning.
In the previous lesson titled "Expressions and Operators" (see Resources), I taught you about expressions, arithmetic operators, and equality operators.
In this lesson, I will teach you about:
I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.
Once you have mastered Alice, 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.
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
We have been using the sequence structure since early in the course. 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.
Obviously, the sequence structure is the simplest of the three.
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.
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 cycle 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 support by Alice 2.0, so you won't learn about them in this series of tutorial lessons on Alice.
In this lesson, I will present and explain three simple programs. (You may download executable versions of the programs through Resources.) The first program, named Alice0165a is designed to teach you about sequence and selection structures.
The second program named Alice0165b is designed to teach you about the loop structure.
The third program named Alice0165c is designed to teach you about the multiple choice composite structure.
Almost all of the sample programs that I have presented in the earlier lessons in this series of tutorials have been constructed using the sequence structure. Therefore, I won't provide another sample program to illustrate that structure alone. I will simply refer you back to earlier lessons for numerous sample programs.
The sample programs in this lesson will combine the sequence structure with the selection structure and the loop structure.
The program named Alice0165a illustrates the use of a selection structure as one of the elements in a sequence structure.
The user is asked to enter an integer as shown in Figure 4.
Figure 4. User input dialog for program named Alice0165a.
Making a decision
The selection structure uses the value of the integer provided by the user to make a decision.
The decision is used to display one or the other of two different messages. The decision is made on the basis of whether the user input is even or odd.
The program output for even input
Figure 5 shows the output produced by the program when the user enters an even integer value.
Figure 5. Program output for even input in program named Alice0165a.
The program output for odd input
Figure 6 shows the output produced by the program when the user enters an odd integer value.
Figure 6. Program output for odd input in program named Alice0165a.
Creating a selection structure in Alice
To create a selection structure in Alice, begin by dragging the if tile from the bottom of the Alice development screen and dropping it at the appropriate location in the edit pane. You will be required to select a placeholder value of true or false. This will result in the skeleton code shown in Figure 7 being inserted into the edit pane.
Figure 7. Skeleton code for a selection structure.
The conditional clause
The placeholder value (true in Figure 7) and the parentheses that surround it in the skeleton code is often called the conditional clause. Once the skeleton appears in your code, you can replace the placeholder value with any expression that will evaluate to a value of type Boolean.
The expression that you place in the conditional clause is the expression that will be evaluated to determine which part of the selection structure to execute. If the expression in the conditional clause evaluates to true, the code between the curly braces before the else clause will be executed. If the expression in the conditional clause evaluates to false, the code in the body of the else clause will be executed.
Omitting the else clause
In languages such as Java, C++, and C#, if you don't need the else clause, you can simply omit it. However, it will always be there in Alice. You cannot omit it. If you don't need it, just don't put any code into it, and it will be essentially ignored at runtime.
Source code for the program named Alice0165a
The source code for the program named Alice0165a is presented in Listing 1 near the end of the lesson. All of the code is contained in the main method. You can also download an executable version of the program (see Resources).
Create and run the program
To create and run this program, either download the executable version (see Resources) or:
Two variables
The code in Listing 1 declares the following two variables:
The initial values of the variables are immaterial because they are set to current values by program code when the program is run.
Code in the main method
The code in the main method consists of a sequence structure containing three actions:
|
Program rationale
The rationale for the program is that the remainder produced by dividing an even integer by 2 will be zero, and the remainder produced by dividing an odd integer by 2 will not be zero. Therefore, information about whether or not the value of the remainder is zero can be used to determine if the user input integer is even or odd. That rationale is used in the selection structure to determine whether to display the word Even, as shown in Figure 5, or the word Odd as shown in Figure 6.
The selection structure
The behavior of the selection structure can be paraphrased as follows:
If the expression in the conditional clause evaluates to true, execute the statements inside the curly braces following the conditional clause. Else (short for otherwise) execute the statements inside the curly braces following the word else.
In this program, if the value contained in the variable named testResult is the Boolean value true, the method named say is called on the penguin object to display the word Even above the penguin's head as shown in Figure 5.
If the value contained in the variable named testResult is the Boolean value false, the method named say is called on the penguin object to display the word Odd above the penguin's head as shown in Figure 6.
Program can be much longer
This simple program only contains one statement inside each of the two sets of curly braces in the selection structure. In general, however, any sequence of actions of any length can be included inside the curly braces. The sequence of actions may consist of a sequence of statements. There may also be other selection and loop structures nested in that sequence of actions.
If your program has a number of steps which must be executed multiple times, the most likely approach for accomplishing this is to use a repetition or loop structure.
This program, which is named Alice0165b illustrates the use of a loop structure as one of the elements in a sequence structure.
As in the previous program, the user is asked to enter an integer as shown in Figure 4. If the user enters an even integer, the program displays the image shown in Figure 8 for two seconds, and then returns to the image shown in Figure 4 to ask the user to enter another integer.
Figure 8. Program output for even input to program name Alice0165b.
The process of displaying the image shown in Figure 8 for two seconds and then asking the user to enter another integer continues for as long as (while) the user continues entering even integer values.
Program output for odd integer
When the user enters an odd integer, the penguin speaks, turns, and walks away as shown in Figure 9.
Figure 9. Program output for odd input to program named Alice0165b.
When the penguin has walked 100 meters, (which takes a fairly long time because penguins walk very slowly), the program terminates.
Creating a skeleton while loop in Alice
To create a while loop structure in Alice, begin by dragging the while tile (not the loop tile) from the bottom of the Alice development screen and dropping it at the appropriate location in the edit pane. (I will have more to say about the loop tile later.) As with the selection structure, you will be required to select a placeholder value of true or false. This will result in the skeleton code shown in Figure 10 being inserted into the edit pane.
Figure 10. Skeleton code for a loop structure.
The conditional clause
As with a selection structure discussed earlier, a loop structure has a conditional clause. The placeholder value (true in Figure 10) and the parentheses that surround it in the skeleton code constitute the conditional clause. Once the skeleton for the loop structure appears in your code, you can replace the placeholder value with any expression that will evaluate to a value of type Boolean.
The expression that you place in the conditional clause is the expression that will be evaluated to determine if the code in the body of the loop structure (the code between the curly braces in Figure 10) will be executed one time, or if the loop structure will terminate.
If the expression in the conditional clause evaluates to true, the code in the body of the loop will be executed once. If the expression in the conditional clause evaluates to false, the loop will terminate immediately causing the code in the body of the loop to be skipped and causing the next statement following the body of the loop to be executed.
Source code for the program named Alice0165b
The source code for the program named Alice0165b is presented in Listing 2 near the end of the lesson. All of the code is contained in the main method. You can also download an executable version of the program (see Resources).
To create and run this program, either download the executable version, or:
Two variables
As was the case with the previous program, the code in Listing 2 declares the following two variables:
Once again, the initial values of the variables are immaterial because they are set to current values by program code when the program is run.
Code in the main method
The code in the main method consists of the following sequence of actions:
Getting user input
This program uses the same code as the previous program to:
This code appears at two different locations within the program.
|
The priming read
The code that appears before the beginning of the while loop in Listing 2 is commonly known as a priming read. (This terminology comes from the concept of "priming the pump." If you don't know about priming pumps, don't worry about it. Knowing about pumps is not a requirement for learning how to program.) The purpose of the priming read is to get the first input value (from the user in this case) before entering the loop so that the value can be used to determine the behavior of the loop during the first iteration.
The while loop
As described earlier, if the value of testResult is true, the code inside the body of the loop is executed once. The code in the body of the loop in Listing 2 consists of two sequential actions:
After the user enters another integer value and it is tested to produce and store a Boolean value, control goes back to the top of the loop where the value of testResult is tested for true or false again.
If the value of testResult is still true when the test is performed, the code in the body of the loop is executed one more time. This looping process continues until the value of testResult becomes false, at which time the body of the loop is skipped, and the loop structure terminates.
Termination of the loop and the program
When the value of testResult is found to be false, the code in the body of the loop is skipped, the looping action ceases (the loop terminates) and the statements in the doTogether block following the while loop structure is executed. (See Figure 9.) You already know about code like this from previous lessons, so I won't explain it here. When the code in the doTogether block finishes execution, the program terminates. (In general, the loop will exit or terminate when the conditional clause evaluates to false.)
There is another point that I need to make before leaving the topic of loops. The loop structure in Listing 2 was implemented using a while loop. A while loop is known as a pre-test or entry-condition loop. This is because the conditional test is performed before the code in the body of the loop is executed.
If the test returns true, the code in the body of the loop is executed and the test is performed again. When the test returns false, even if it is first time that the test is performed, the code in the body of the loop is skipped and control exits the loop structure. Therefore, if the test returns false the first time that it is performed, the code in the body of the loop won't be executed.
Other programming languages such as Java, C++, and C# also have an exit-condition loop, known as a do-while loop. The major significance of the exit-condition loop is that the code in the body of the loop will be executed at least once, even if the test returns false the first time that it is performed. This is because the test is performed after the body of the loop has already executed once. Alice does not have an exit-condition loop.
If you drag the loop tile (instead of the while tile) from the bottom of the Alice development screen and drop it into the edit pane, a different kind of loop will be created. This kind of loop is commonly called a for loop. I will explain in detail how to use a for loop in a future lesson.
In general, a for loop is also an entry-condition loop. The code in the body of the loop will continue to execute for as long as the conditional clause evaluates to true. There are no exit-condition loops in Alice.
A particularly important composite structure is the nested combination of several if-else structures to form a sort of multiple choice structure.
The if-else-if structure is illustrated by the program named Alice0165c. A complete listing of the program is provided in Listing 3. You can also download an executable version of the program (see Resources).
Ask the user to enter an integer
This program asks the user to enter an integer between 1 and 3 inclusive as shown in Figure 11.
Figure 11. User input dialog for program named Alice0165c.
Display a message regarding a valid input integer
Figure 12 shows typical program output for the case where the user input is in the range of 1 through 3 inclusive. (The image in Figure 12 resulted from a user input value of 2.)
Figure 12. Typical output for input in the range of 1 through 3 inclusive for program Alice0165c.
Display an error message
The error message shown in Figure 13 is displayed if the integer value entered by the user is outside the range of 1 through 3 inclusive.
Figure 13. Output for input outside the range of 1 through 3 inclusive for program Alice0165c.
Source code for the program named Alice0165c
Please turn your attention to the source code shown in Listing 3.
None of the code in Listing 3 is new to you. You have seen all of this code before in previous programs in this and earlier lessons. The thing that is new about the code in Listing 3 is the organization of the code.
Although the user is requested to enter an integer value between 1 and 3 inclusive, she is free to enter any value she wishes to enter. The value entered by the user is stored in the variable named userInputValue.
Nested selection structures
The program uses three nested selection structures to test the value stored in the variable named userInputValue and to display one of the following messages as a result:
The choice of message to display depends on the value stored in the variable named userInputValue. Perhaps this will illustrate why I sometimes refer to this kind of structure as a sort of multiple choice structure. (See Figure 12 and Figure 13 for examples of two of the messages in the above list being displayed.)
Trace through the code
If you start tracing through the code at the first occurrence of the word if in Listing 3, you will see that the conditional clause contained in the first selection structure tests to determine if the value stored in the variable named userInputValue is equal to 1. If so, the first message in the above list is displayed and control transfers to the next statement following the final curly brace in the light blue area in Listing 3. However, since there is no statement following that curly brace, the program terminates at that point.
Value not equal to 1
If the value stored in the variable named userInputValue is not equal to 1, control transfers to the else clause belonging to that selection structure . However, that else clause contains another selection structure beginning with the word if. This time, the conditional clause tests to determine if the value stored in the variable named userInputValue is equal to 2. If so, the second message in the above list is displayed and control transfers to the next statement following the final curly brace in the light blue area in Listing 3.
Value not equal to 2
If the value is not equal to 2, control transfers to the else clause of that selection structure, which contains another selection structure. This time, the conditional clause tests to determine if the value stored in the variable named userInputValue is equal to 3. If so, the third message in the above list is displayed and control transfers to the next statement following the final curly brace in the light blue area in Listing 3.
Value equal to 1, 2, or 3
Therefore, at each stage, if the expression in the conditional clause is true, the program displays one of the first three messages in the above list, and transfers control to the next statement following the final curly brace in the light blue area in Listing 3.
Value not equal to 3
If the conditional clause in the third stage is false, control transfers to the else clause of the third selection structure. However, that else clause does not contain another selection structure. Instead, the code in that else clause causes the penguin to display the fourth message in the above list. (See Figure 13.) Following that, control transfers to the next statement following the final curly brace in the light blue area in Listing 3.
|
Study this structure carefully
You should study this structure until you understand it completely. It will turn up again and again in the programs that you will write once you get serious about creating animation programs using Alice.
Executable versions of the programs that I explained in this lesson are available for downloading (see Resources). I encourage you to either download those programs, or copy the code from Listings 1 through 3 into your Alice development environment and play it. Experiment with the code, making changes, and observing the results of your changes.
In this lesson, I taught you about the following topics:
In future lessons, I will teach you about:
So stay tuned. There is lots of fun ahead.
Beginning with the program named Alice0165b, create a new program.
The behavior of the new program is the same as the behavior of the original program except that the program keeps looping for as long as the user enters odd integers. (The behavior for even and odd is switched relative to the program named Alice165b.)
When the user enters an odd integer, the program displays an image similar to that shown in Figure 8 for two seconds. (Cause the penguin to say "Odd, keep on looping.") Then the program returns to the image shown in Figure 4 to ask the user to enter another integer.
When the user enters an even integer, the penguin speaks, turns, and walks away in a manner similar to that as shown in Figure 9. (Cause the penguin to say "Even, I'm outa here.")
Save your world in a file named Alice165LabProjA.a2w and be prepared to deliver it to your instructor in whatever manner the instructor specifies.
Make certain that your preferences are set to Java Style in Color.
Select Export Code For Printing... on the File menu and save your source code in a file named Alice165LabProjA.html. Also be prepared to deliver this file to your instructor in whatever manner the instructor specifies.
View a movie of the lab project
You can download and play a small, low-quality movie of my version of the lab project as it being executed from the Resume button (see Resources). This movie was designed to give you a rough idea of how your program should behave. The movie was purposely recorded in low-quality format in a small window in order to reduce the file size and hence reduce the download time.
Because of the low quality of the movie, the execution of your program should provide much smoother animation than the movie, and should be less grainy than the movie. Also, because of the low quality of the movie, the timing in the movie doesn't necessarily match the duration times specified for the lab project.
The movie was terminated early when the penguin began to walk away rather than to waste bandwidth watching the penguin walk and walk.
I attempted to synchronize the beginning of the recording with the beginning of the program execution by starting, then quickly pausing, and then resuming the execution. If you watch closely, when the movie starts running, you will see the mouse pointer click the Resume button, and the movie will show one complete pass through the program.
You should view this movie in its original size. If you allow the media player to enlarge it, the quality will be poor.
General resources
Resources from earlier lessons in the series titled "Learn to Program using Alice"
Downloads
Listing 1. Source code for the program named Alice0165a.
Alice0165a's CodeCreated by: Dick BaldwinworldMethods
|
Listing 2. Source code for the program named Alice0165b.
Alice0165b's CodeCreated by: Dick BaldwinworldMethods
|
Listing 3. Source code for the program Alice0165c.
Alice0165c's CodeCreated by: Dick BaldwinworldMethods
|
Copyright 2007, Richard G. Baldwin. Faculty and staff of public and private non-profit educational institutions are granted a license to reproduce and to use this material for purposes consistent with the teaching process. This license does not extend to commercial ventures. Otherwise, reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
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.
-end-