## Sequence, Selection, and Loop Structures

Revised:  February 3, 2007
By Richard G. Baldwin

File:  Pf00170.htm
Practice Text

## Preface

This lesson was written specifically for the benefit of my students in COSC 1315, Fundamentals of Programming.  The lesson was written under the assumption that those students have no prior programming knowledge when they enroll in the course.

Another browser window

I recommend that you open another copy of this document in a separate browser window so that you can view the code and the discussion of that code at the same time.

## Structured Programming

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 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:

• Sequence
• Selection or decision
• Loop or iteration

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.  (See the lesson entitled The sequence Structure.)  Basically we can describe the sequence structure using the pseudocode shown in Figure 1.

 Enter Perform one or more actions in sequence Exit Figure 1

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

With the exception discussed below, 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.

 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 Figure 2

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 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(Note that this pseudocode applies to an entry-condition loop, which I will explain in more detail later.  The pseudocode would also be different for an exit-condition loop, which I will also describe in more detail later.)

 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 Figure 3

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:

• One or more actions are performed in sequence
• The condition is tested again.

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

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

• Switch-case
• Do until

They are not required for the solution of programming logic problems.  Thus, they don't qualify as fundamental programming concepts.  However, they are very widely used and I may include them in a lesson on miscellaneous topics later.

## Sample Programs

### The sequence structure in code

Listing 12 contains an object-oriented version of a program that you first saw in an earlier lesson entitled The sequence Structure.  The earlier version was implemented solely in the global main function.

The version in Listing 12 is implemented using an approach that avoids the use of all global functions other than the global main function.

Similar to previous code

The code in the global main function and the code in the function named classMain is identical to code that you have seen in numerous sample programs in earlier lessons.

Therefore, I won't discuss that code here.  You can view that code in Listing 12.

Sample sequence structure

The sequence structure is implemented in the instance function named doSomething, and I will discuss that function here.  The doSomethng function is shown in it entirety in Listing 1.

 void doSomething(){ cout << "Hello Viet Nam\n"; cout << "Hello Iraq\n"; cout << "Hello America\n"; cout << "Hello World\n"; }//end doSomething function Listing 1

Executes a sequence of statements

The function named doSomething executes a sequence of statements and then terminates.

The statements in the sequence do not include decisions or loops.

In this simple case, there are no other sequence, selection, or loop structures in the sequence.

The program output

Each statement in the sequence produces one line of output text on the screen as shown below:

Hello Viet Nam
Hello Iraq
Hello America
Hello World

This function named doSomething will serve as the basis for the next two programs to be discussed in this lesson.

### The selection structure in code

The next program named Structures02 illustrates the use of a selection structure as one of the elements in a sequence structure.

The user is asked to enter an integer and then the selection structure uses the value of the integer 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

The program displays the following output on the screen when the user input is 4, an even value.  (The output that is new to this program is highlighted in boldface.)

Hello Viet Nam
Hello Iraq
Enter an integer: 4
Hello America
Hello World

The program displays the following output on the screen when the user input is 5, an odd value:

Hello Viet Nam
Hello Iraq
Enter an integer: 5
Hello America
Hello World

Will discuss the code in fragments

I will discuss this program code in fragments.  A complete listing of the program is provided in Listing 10 near the end of the lesson.

Two functions same as before

The global main function and the function named classMain are identical to functions having the same name in numerous sample programs in previous lessons, so I won't discuss them further here.  You can view those functions in Listing 10.

The doSomething function

I will begin the discussion with the instance function named doSomething.  This function is shown in its entirety in Listing 2.

 void doSomething(){ cout << "Hello Viet Nam\n"; cout << "Hello Iraq\n"; doSelection(); cout << "Hello America\n"; cout << "Hello World\n"; }//end doSomething function Listing 2

A sequence structure in the doSomething function

The doSomething function executes a sequence structure consisting of five action elements.  Then the function terminates.

Each of the first two action elements in the sequence displays a message on the screen similar to the previous program.

These two messages constitute the first two lines of text in the output shown under program output earlier.

Something new

The third action element in the sequence executes a selection structure by calling a function named doSelection.

As you will see later, the doSelection function executes a sequence structure followed by a selection structure.

(Although this selection structure was implemented in a separate function, it could just as well have been implemented as inline code.)

Last two action elements same as before

When the doSelection function returns control to the doSomething function:

• The doSomething function executes the remaining two action elements in the five-element sequence.
• Then the doSomething function terminates.

Each of the last two action elements displays a message on the screen the same as in the previous program.

These two messages constitute the last two lines of output shown under program output earlier.

The doSelection function

The doSelection function, which begins in Listing 3, executes a sequence structure consisting of three action elements followed by a selection structure.

 void doSelection(){ //Begin sequence structure int temp = 0; cout << "Enter an integer: "; cin >> temp; //End sequence structure Listing 3

The three elements in the sequence structure are shown in Listing 3.

The purpose of this sequence structure is to get and save an integer input value from the user.

The code in Listing 3 produces the third line of output text shown under program output earlier.

The selection structure

The selection structure is shown in Listing 4.

 //Begin selection structure if(temp % 2 == 0){ cout << "Your number was even" << endl; }else{ cout << "Your number was odd" << endl; }//end else //End selection structure }//end doSelection Listing 4

The code in Listing 4 makes a decision.  The result of the decision process depends on whether the user input was even or odd.

The relational expression ==

I realize that we haven't covered relational and logical expressions in detail yet.  That is the topic for a future lesson.  For now, just accept the fact that the following expression will return true if A is equal to B, and will return false otherwise:

A == B

If the input is even, the code in the selection structure in Listing 4 displays a message indicating that the input was even.

If the input is odd, the code in the selection structure displays a message indicating that the input is odd.

The code in Listing 4 produces the fourth line of output shown under program output earlier.

Distinguishing even from odd ...

Note the use of the modulus operator to determine if the user's input value is even or odd.

The code in Listing 4 uses the modulus operator to get the remainder produced by dividing the user's input value by 2.

• If the input value was even, the remainder will be 0.
• If the input value was odd, the remainder will be 1.

Test for remainder value of 0

The conditional clause in the if statement in Listing 4 tests to determine if the remainder is 0.

• If the remainder value is 0, Listing 4 produces the message indicating that the input was even.
• If the remainder value is not 0, Listing 4 produces the message indicating that the input was odd.

Terminate and return control

After completing the test and displaying the appropriate message, the doSelection function terminates and returns control to the doSomething function shown in Listing 2.

The doSomething function finishes executing the action elements in its sequence and then terminates.

### The loop structure in code

The next program named Structures03 illustrates sequence, selection, and loop structures all in a single program.

The program executes a loop structure as one of the action elements in a sequence structure.

The loop structure executes a selection structure as one of the action elements during each iteration of the loop.

Are we there yet?

The loop structure uses the selection structure to decide when to quit looping.

The user is asked to enter an integer during each iteration of the loop.

The loop structure continues to loop and request new input for as long as the user continues to enter odd integers.

When the user enters an even integer, the loop structure terminates displaying a goodbye message on the way out.

Program output

The following text is typical of the output that appears on the screen when the program is run.  The output that is new to this program is highlighted in boldface.

Hello Viet Nam
Hello Iraq
Enter an even integer to quit
or an odd integer to loop: 1
Enter an even integer to quit
or an odd integer to loop: 3
Enter an even integer to quit
or an odd integer to loop: 5
Enter an even integer to quit
or an odd integer to loop: 6
I'm outta here!
Hello America
Hello World

Will discuss in fragments

As before, I will discuss this program in fragments.  A complete listing of the program is shown in Listing 11 near the end of the lesson.

Will begin with the doSomething function

The global main function and the function named classMain are identical to functions having the same names that I have discussed in numerous sample programs in previous lessons, so I won't discuss them again here.  You can view those functions in Listing 11.

I will begin the discussion with the instance function named doSomething shown in its entirety in Listing 5.

 void doSomething(){ cout << "Hello Viet Nam\n"; cout << "Hello Iraq\n"; //Execte the loop structure. doLoop(); cout << "Hello America\n"; cout << "Hello World\n"; }//end doSomething function Listing 5

A loop is nested in the sequence

The doSomething function executes a sequence of statements and then terminates.

One of the action elements in the sequence is a loop structure, which is implemented as a function named doLoop.

Although the loop structure is implemented in a function, it could have been implemented as inline code just as well.

The doLoop function

The doLoop function, which begins in Listing 6, consists of a sequence structure followed by a loop structure.  The sequence structure is shown in Listing 6.

 void doLoop(){ //Begin sequence structure. bool quit = false; int temp = 0; //End sequence structure Listing 6

Declare and initialize two local variables

The code in Listing 6 declares and initializes two local variables that are used later by the loop structure.

The loop control variable named quit

One of the variables named quit is used in the conditional test in the loop structure.  Variables used for this purpose are often referred to as loop control variables.

The variable named quit is initialized to false.

The program continues to loop for as long as the variable named quit continues to have a value of false.

The value of quit is controlled by the return value from a function named doSelection.

The function named doSelection implements a selection structure.

When the value of quit becomes true, the loop terminates.

Deciding when to quit looping

The loop structure shown in Listing 7 uses a selection structure to decide when to quit looping.

 //Begin loop structure while(quit != true){ cout << "Enter an even integer to quit\n" << "or an odd integer to loop: "; cin >> temp; //Execute a selection structure quit = doSelection(temp); }//end while loop //End loop structure cout << "I'm outta here!" << endl; }//end doLoop Listing 7

The user is asked to enter an integer during each iteration of the loop.

The relational expression !=

Once again, I realize that we haven't covered relational and logical expressions in detail yet.  For now, just accept the fact that the following expression will return true if A is not equal to B, and will return false otherwise:

A != B

The conditional clause

The program continues to loop and ask for more inputs for as long as the value of quit is not equal to true.

The value of quit remains false (not true) for as long as the user enters odd integers.  (See Listing 8.)

When the user enters an even integer, the value of quit becomes true.

Terminate the loop when quit becomes true

When the value of quit becomes true, the loop structure terminates.  (See Listing 7.)

When the loop structure terminates, the function named doLoop terminates and returns control to the function named doSomething.

At that point, the doSomething function executes a couple more action elements in the sequence and then terminates.  (See Listing 5.)

The doSelection function

The function named doSelection is called once during each iteration of the loop.

The doSelection function is shown in its entirety in Listing 8.

 bool doSelection(int data){ bool result; //Begin selection structure if(data % 2 == 0){ result = true; }else{ result = false; }//end else //End selection structure return result; }//end doSelection Listing 8

User input is incoming parameter

The user input value is passed as a value parameter to the doSelection function each time it is called.

The function executes a selection structure to decide whether to return true or false.

• If the user input value is even, the function returns true.
• Otherwise, it returns false.

Using the return value from the doSelection function

As you can see in Listing 7, the return value from the doSelection function is assigned to the quit variable during each iteration.

When a true value is returned by the doSelection function and assigned to quit, the loop terminates the next time it tests the value of quit.

An alternative approach

Note that this program could also have been written by writing the conditional clause in Listing 7 as shown below:

while(quit == false){

### A pre-test or entry-condition loop

There is one additional point that I need to make before leaving the topic of loops.  All of the loop structures in this lesson were implemented using a  while loop.  A while loop is  know as an 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.  If the test returns false the first time that it is performed, the code in the body of the loop won't be executed.

An exit-condition loop

C++ also has 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.  I will explain the do-while loop in a future lesson.

A for loop

C++ also has a different entry-condition loop known as a for loop.  I will also explain the for loop in a future lesson.

### The if-else-if combination structure

A particularly important combination structure is the combination of several if else structures to form a sort of multiple choice structure.

(Note that the same result can sometimes be achieved more conveniently using a switch-case structure.)

The if-else-if is illustrated by the program named Structures04.  A complete listing of the program is provided in Listing 13.

Ask the user to enter an integer

This program asks the user to enter an integer between 1 and 3.

Then the program displays a message related to the value of the integer.

An error message is displayed if the integer is not one of the specified values.

Sample output

The program displays the following output on the screen for several different input values:

Enter an integer, 1-3 inclusive: 0
Invalid input

Enter an integer, 1-3 inclusive: 1
Thanks for the 1

Enter an integer, 1-3 inclusive: 2
Thanks for the 2

Enter an integer, 1-3 inclusive: 3
Thanks for the 3

Enter an integer, 1-3 inclusive: 4
Invalid input

Will discuss in fragments

Large portions of this program are identical to code that you have seen in previous programs, so I won't rehash that material here.  I will only discuss the material that is new to this program.

The doSomething function

The new material is contained in the doSomething function, which is shown in its entirety in Listing 9.

 void doSomething(){ //Begin sequence structure int temp = 0; cout << "Enter an integer, 1-3 inclusive: "; cin >> temp; //End sequence structure //Begin nested selection structures if(temp == 1){ cout << "Thanks for the 1" << endl; }else if(temp == 2){ cout << "Thanks for the 2" << endl; }else if(temp == 3){ cout << "Thanks for the 3" << endl; }else{ cout << "Invalid input" << endl; }//end else //End selection structure }//end doSomething function Listing 9

Nested selection structures

The code consists of a series of nested selection structures.

Indentation is used in Listing 9 in an attempt to make the nesting more readily understandable.  (Only you can decide whether or not the indentation is effective for that purpose.)

A new if-else structure

In all of the selection structures but the last, a new if-else selection structure forms the body of the else clause of the previous structure.

An input value of 1

If the user input value is 1:

• A message is displayed
• Everything following that location in the structure is skipped.  (The entire structure terminates.)

If the user input value is not 1, a new test is performed.

An input value of 2

The new test determines if the user input value is 2.

If the user input value is 2:

• A message is displayed
• Everything following that location in the structure is skipped.  (Once again, the entire structure terminates.)

If the user input value is not 2, a new test is performed.

An input value of 3

The new test determines if the user input value is 3.

If the user input value is 3:

• A message is displayed
• Everything following that location in the structure is skipped.  (Once again, the entire structure terminates.)

An invalid input

If the user input value is not 3, it is concluded that:

• All possible values of 1, 2, or 3 have been tested
• The user input cannot possibly be one of those three values

The final else clause

In that case, the final else clause is executed.

The final else clause displays a message indicating that the input is not valid.

## Complete Program Listings

Complete listings of the programs discussed in this lesson are shown below.

 /*File: Structures02.cpp This C++ program illustrates the sequence structure with a selection structure as one of the elements in the sequence. The selection structure asks the user to enter an integer and then displays one of two different messages depending upon whether the user input is even or odd. The program displays the following output on the screen when the user input is even: Hello Viet Nam Hello Iraq Enter an integer: 4 Your number was even Hello America Hello World The program displays the following output on the screen when the user input is odd: Hello Viet Nam Hello Iraq Enter an integer: 5 Your number was odd Hello America Hello World ************************************************/ #include using namespace std; class Structures02{ public: static void classMain(){ Structures02* ptrToObject = new Structures02(); ptrToObject -> doSomething(); }//End classMain function //-------------------------------------------// //An instance function of the Structures02 // class made up of a sequence structure and // a selection structure. void doSelection(){ //Begin sequence structure int temp = 0; cout << "Enter an integer: "; cin >> temp; //End sequence structure //Begin selection structure if(temp % 2 == 0){ cout << "Your number was even" << endl; }else{ cout << "Your number was odd" << endl; }//end else //End selection structure }//end doSelection //-------------------------------------------// //An instance function of the Structures02 // class void doSomething(){ //This function executes a sequence of // statements and then terminates. One of // the elements in the sequence is a // selection structure, which is implemented // as a function, but could be implemented // as inline code just as well. cout << "Hello Viet Nam\n"; cout << "Hello Iraq\n"; doSelection(); cout << "Hello America\n"; cout << "Hello World\n"; }//end doSomething function };//End Structures02 class //---------------------------------------------// int main(){ Structures02::classMain(); return 0; }//end main Listing 10

 /*File: Structures03.cpp This C++ program illustrates the use of a sequence structure that executes a loop structure as one of the action elements in the sequence. The loop structure executes a selection structure as one of the action elements during each iteration of the loop. Thus, this one program illustrates all three of the primary structures: sequence selection loop The following is a typical output that appears on the screen when the program is run: Hello Viet Nam Hello Iraq Enter an even integer to quit or an odd integer to loop: 1 Enter an even integer to quit or an odd integer to loop: 3 Enter an even integer to quit or an odd integer to loop: 5 Enter an even integer to quit or an odd integer to loop: 6 I'm outta here! Hello America Hello World ************************************************/ #include using namespace std; class Structures03{ public: static void classMain(){ Structures03* ptrToObject = new Structures03(); ptrToObject -> doSomething(); }//End classMain function //-------------------------------------------// //An instance function of the Structures03 // class that executes a selection structure. // The function receives an incoming parameter // of type int. It returns true if the incoming // parameter is even and false if the incoming // parametr is odd. bool doSelection(int data){ bool result; //Begin selection structure if(data % 2 == 0){ result = true; }else{ result = false; }//end else //End selection structure return result; }//end doSelection //-------------------------------------------// //An instance function of the Structures03 // class made up of a sequence structure // followed by a loop structure. The loop // structure uses a selection structure // to decide when to quit. The user is // asked to enter an integer during each // iteration of the loop structure. When // the user enters an even integer, the // loop structure terminates. void doLoop(){ //Begin sequence structure. bool quit = false; int temp = 0; //End sequence structure //Begin loop structure while(quit != true){ cout << "Enter an even integer to quit\n" << "or an odd integer to loop: "; cin >> temp; //Execute a selection structure quit = doSelection(temp); }//end while loop //End loop structure cout << "I'm outta here!" << endl; }//end doLoop //-------------------------------------------// //An instance function of the Structures03 // class void doSomething(){ //This function executes a sequence of // statements and then terminates. One of // the elements in the sequence is a loop // structure, which is implemented // as a function, but could be implemented // as inline code just as well. cout << "Hello Viet Nam\n"; cout << "Hello Iraq\n"; //Execte the loop structure. doLoop(); cout << "Hello America\n"; cout << "Hello World\n"; }//end doSomething function };//End Structures03 class //---------------------------------------------// int main(){ Structures03::classMain(); return 0; }//end main Listing 11

 /*File: Structures01.cpp This C++ program illustrates the sequence structure The program displays the following output on the screen: Hello Viet Nam Hello Iraq Hello America Hello World ************************************************/ #include using namespace std; class Structures01{ public: static void classMain(){ Structures01* ptrToObject = new Structures01(); ptrToObject -> doSomething(); }//End classMain function //-------------------------------------------// //An instance function of the Structures01 // class void doSomething(){ //This function executes a sequence of // statements and then terminates. The // statements in the sequence do not // include decisions or loops. cout << "Hello Viet Nam\n"; cout << "Hello Iraq\n"; cout << "Hello America\n"; cout << "Hello World\n"; }//end doSomething function };//End Structures01 class //---------------------------------------------// int main(){ Structures01::classMain(); return 0; }//end main Listing 12

 /*File: Structures04.cpp This C++ program illustrates the if else if structure. The program asks the user to enter an integer between 1 and 3 and then displays a message related to the value of the integer. An error message is displayed if the integer is not one of the specified values. The program displays the following output on the screen for several different input values: Enter an integer, 1-3 inclusive: 0 Invalid input Enter an integer, 1-3 inclusive: 1 Thanks for the 1 Enter an integer, 1-3 inclusive: 2 Thanks for the 2 Enter an integer, 1-3 inclusive: 3 Thanks for the 3 Enter an integer, 1-3 inclusive: 4 Invalid input ************************************************/ #include using namespace std; class Structures04{ public: static void classMain(){ Structures04* ptrToObject = new Structures04(); ptrToObject -> doSomething(); }//End classMain function //-------------------------------------------// //An instance function of the Structures04 // class void doSomething(){ //Begin sequence structure int temp = 0; cout << "Enter an integer, 1-3 inclusive: "; cin >> temp; //End sequence structure //Begin selection if(temp == 1){ cout << "Thanks for the 1" << endl; }else if(temp == 2){ cout << "Thanks for the 2" << endl; }else if(temp == 3){ cout << "Thanks for the 3" << endl; }else{ cout << "Invalid input" << endl; }//end else //End selection structure }//end doSomething function };//End Structures04 class //---------------------------------------------// int main(){ Structures04::classMain(); return 0; }//end main Listing 13

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