Looping and Branching
More Design
Three basic concepts:
- Sequence
- Selection
- Iteration
Sequence
Individual processors are sequential - they carry out instructions in the order that they are held in memory, unless an instruction dictates otherwise. Steps are numbered and carried out in numerical order unless we have a loop or if step. The sequence in the design is vital. Without the design, input may occur in the wrong order. Subsequent processing may fail if the data is not there ready for processing. Purely sequential programs are limited. However, Windows programs are built from many short sequential pieces of code. Their versatility comes from the way they are used.
Selection
We have done some selection - if this is this then do this - else do this - ifend. Boolean value dictates which design branch to follow. These if/else designs can be nested to generate more branches.
if lights are red then stop else if lights are amber then stop if safe to do so else if lights are red and amber then prepare to go else if lights are green then go ifend ifend ifend ifend
Another example.
if car is saloon then if driver is under 25 then premium is 360 else premium is 290 ifend if driver is over 25 then premium is 520 else premium is 440 ifend ifend
Nesting works but can be inefficient where there are a large number of steps. A process to aid the selection of a specific criteria is the case step. This expresses a nested if step in a simpler format.
read in character from keyboard input select case depending on character input 'a' : add 1 to a count 'b' : add 1 to b count 'c' : add 1 to c count 'd' : add 1 to d count 'e' : add 1 to e count else add 1 to non-vowel count selectend
Iteration
The repetition of the same sequence of steps over and over. The loop while step is a pre-conditioned loop that will iterate, potentially forever, unless a criteria is reached that satisfies the while condition. As long as the boolean value is true, the loop will continue. It is only a change to a false value that will end the loop.
In contrast the when loop has the control conditon placed at the end. This is a post-conditioned loop. Iteration ends when the condition becomes true. The when loop is always completed at least once. The while loop may never loop if the pre-condition value is false on first use.
One other loop is for loop. This iterates for a pre-determined number of times. More on that another time.
Designing a Calculator Simulation
Top-level Design
- initialise variables
- loop while there are more operations to carry out
- carry out next operation
- loopend
- write out final answer
| Type | Identifier | Description |
| Real | InputNumber | Number entered |
| Real | RunTotal | Records the running total |
| Character | Operator | Operates on input |
Variable initialisation should not be incorporated into the design until a decision is made on the conditon loop to use.
Refining the Design
Choosing a post-conditioned loop.
1.1 Answer <— 0 1.2 Operator <— + 2.1 Loop 3.1 read in InputNumber 3.2 update RunTotal 3.3 read in Operator 4.1loopend 5.1write out RunTotal
Final Design - making use of the select case method.
1.1 Answer <— 0 1.2 Operator <— + 2.1 Loop 3.1.1 write out "Enter next number: " 3.1.2 read in InputNumber 3.2.1 select case dependant on operator 3.2.2 '+' : RunTotal<—RunTotal + InputNumber 3.2.3 '-' : RunTotal<—RunTotal - InputNumber 3.2.4 '*' : RunTotal<—RunTotal * InputNumber 3.2.5 '/' : RunTotal<—RunTotal / InputNumber 3.2.6 else 3.2.7 write out "Error - input last number and operator and number again." 3.2.8 selectend 3.3.1 write out "Enter operator or = to stop." 4.1 loopend when operator = '=' 5.1.1 write out "The answer is ", RunTotal
Step 3.2.5 can be modified to prevent division by zero. The design is below.
3.2.5.1 '/' : if InputNumber is not equal to 0 3.2.5.2 RunTotal<—RunTotal / InputNumber 3.2.5.3 else 3.2.5.4 write out "Error - cannot divide by 0. Last input ignored" 3.2.5.5 ifend
No allowance has been made as yet for non-numeric or operator input. Watch this space.
Coding the Solution
The when step is coded as a do while loop. e.g.
do
{
statements of loop body;
}
while (condition);
Control condition in brackets. Loop statements in braces unless there is just a single statement. No semi colon after braces.
do
{
ReadIntPr ("Enter first number: ");
Total = Total + NextNumber;
MoreToCome = ReadCharPr ("Any more? Type Y (yes) or N (no).");
}
while (MoreToCome != 'N');
The design case step is coded as a switch statement.
switch (expression)
{
case constant1 : statement sequence;
break;
case constant2 : statement sequence;
break;
default : statement sequence;
}
Constant values of same type. Control condition must evaluate to this same type. Statement is executed until it reaches the break statement. Break moves to the next instruction after the switch statement, otherwise the following case step will be executed. There is no break after the default. The default is executed if there is no match to the condition. If we have an else of 'do nothing' the default can be omitted.
The Solution
//---------------------------------------------------------------------------
#include <vcl.h>
#include "MT262io.h"
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
float InputNumber;
char Operator;
float RunTotal;
InputNumber = 0;
Operator = '+';
do
{
InputNumber = ReadIntPr("Enter next number: ");
switch (Operator)
{
case '+' : RunTotal = RunTotal + InputNumber;
break;
case '-' : RunTotal = RunTotal - InputNumber;
break;
case '*' : RunTotal = RunTotal * InputNumber;
break;
case '/' : if (InputNumber != 0)
RunTotal = RunTotal / InputNumber;
else
WriteStringCr("Cannot divide by 0. Last input ignored!");
break;
default : WriteStringCr("Error! Enter last operator and number again.");
}
Operator = ReadCharPr("Enter operator or = to stop.");
}
while (Operator != '=');
if(Operator='=')
WriteFloatPr("The answer is ", RunTotal);
getchar();
return 0;
}
//---------------------------------------------------------------------------
I didn't get the above to work first time, but I got there without too much trouble and without consulting the Course Team solution.
Comments, suggestions, ideas to
Stuart Banner
