prerequisite knowledge - moodle · web viewthe aim of this topic is to introduce you to iterative...

73
1 __________________________________ ___ Topic 7 High Level Language Constructs 2 ____________________________ __ Contents 7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 7.2 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 7.2.1 The For..Next loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 7.2.2 Nested For loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 7.2.3 Review Question . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 7.3 Formatting output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 7.4 Do Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 7.4.1 Do While..loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 7.4.2 Examples of Do While.. Loop . . . . . . . . . . . . . . . . . . . . . . . . 14 c _ HERIOT-WATT UNIVERSITY 2004

Upload: others

Post on 22-Mar-2020

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

1

_____________________________________

Topic 7

High Level Language Constructs 2______________________________Contents

7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27.2 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

7.2.1 The For..Next loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37.2.2 Nested For loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77.2.3 Review Question . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

7.3 Formatting output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127.4 Do Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

7.4.1 Do While..loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137.4.2 Examples of Do While.. Loop . . . . . . . . . . . . . . . . . . . . . . . . 147.4.3 Do Until..Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187.4.4 Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237.4.5 Programming Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

7.5 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267.5.1 Declaring arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287.5.2 Initialising arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287.5.3 Examples of using arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 307.5.4 Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347.5.5 Worked example programs . . . . . . . . . . . . . . . . . . . . . . . . . 35

7.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417.7 End of topic test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417.8 Exercises – Manipulating Data Structures (Arrays) . . . . . . . . . . . . . . . . . . . 42

Prerequisite knowledgeBefore studying this topic you should be able to describe and use the following constructs in pseudo-code and a suitable high level language:

fixed loops;

conditional loops using simple and complex conditions;

nested loops;

1-D arrays.

Learning Objectives Be able to declare a 1-dimensional array

Be able to access array elements

Be able to manipulate data within arrays using iterative structures

c _ HERIOT-WATT UNIVERSITY 2004

Page 2: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

2

RevisionQ1: An array is described as a structured data type. This means that:

a) Data items are all in orderb) Data items will take up a lot of computer memory c) Data items of the same type are grouped together d) None of the above

Q2: What occurs when a 1-D array is initialised?

a) All array elements are set to the same valueb) All array elements are put into orderc) Only the first array element is set to some value d) Nothing occurs when an array is initialised

Q3: A 1-D array string called Days(0-6) hold the days of the week. The 4th array element is assigned the value Wednesday. The correct statement for this is:

a) Days(4) = "Wednesday" b) Days(3) = Wednesday c) Days(4) = Wednesday d) Days(3) = "Wednesday"

Q4: An array called List(5) contains the integers 1 to 6 in sequence. If the 2nd and 4th elements are now assigned the values 8 and 9 respectively, the array List will now contain:a) 1, 2, 3, 8, 5, 9

b) 1, 2, 8, 4, 9, 6c) 1, 8, 3, 9, 5, 6d) 8, 2, 9, 4, 5, 6

Q5: All array elements have to be set with similar values. The process to accomplishthis is called:

a) Sequenceb) Selection c) Iterationd) None of the above

c _ HERIOT-WATT UNIVERSITY 2004

Page 3: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

3

7.1 IntroductionAn important aspect of this topic is the 1-dimensional array. Declaring and initialising arrays are introduced together with how data is manipulated within arrays using various looping structures. Each sub topic has working solutions to the example programs thus providing a suitable environment for building confidence in writing programs before the final topic, dealing with standard algorithms is covered.

7.2 IterationThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of programming is the execution of blocks of code many times over.

Iteration is a fundamental part of almost every program and is one of the most useful features of programming. You do not want a computer to produce one payslip, but many payslips; to add up just two numbers but thousands of numbers; to put in order just two items but thousands of items.There are three different looping constructs you can use in True Basic: :

1 For...Next loop

2 Do...While loop

3. Do...Until loop

Most loops have the following characteristics in common:

initialization

a condition which evaluates either to TRUE or FALSE

a counter that increments or decrements by discrete values.

7.2.1 The For..Next loop

The FOR keyword marks the beginning of the code which will be repeated according to the conditions supplied following the FOR.

When incrementing, the general form of the statement is:

FOR counter = initial_value TO final_value STEP value

When decrementing, the general form of the statement is:

FOR counter = initial_value TO final_value STEP -ve value

Note:

1. The initialisation statement is carried out only once when the loop is first entered i.e. initialise counter to initial value

2. . The condition is tested before each run through the body of the loop. The first test is mmediately after initialisation, so if the test fails the statements in the body are not run. An incrementing loop terminates when counter > final, while a decrementing loop terminates when counter < final

c _ HERIOT-WATT UNIVERSITY 2004

Page 4: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

4

3. An increment or decrement of the counter variable is executed after the loop body and before the next test. The value of the counter is incremented or decremented by the step value.

4. the value of counter must not be changed in any statements within the body of the loop

5. changing the value of final within the loop will have no effect on how many times the loop is executed

6. after the loop has terminated, the value of counter is undefined

7. counter may be any ordinal type e.g. integer, char

Figure 7.1:

The initial and final states may be constants, variables or expressions e.g.

FOR counter = (min+7) to (max-5)

The following examples will show the FOR…NEXT loop in operation.

Example 1: Converting inches to centimetresProblem: Write a program that will convert inches to centimetres for a range of valuesand using an increment of 5. Use the FOR…NEXT loop and output the results in tabular form. Use the conversion factor 2.54 centimetres to the inch. Solution

The algorithm is shown below

c _ HERIOT-WATT UNIVERSITY 2004

Page 5: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

5

1. For counter = 1 to 50 step 5

2. Calculate conversion to centimetres using the factor 2.54

3. Output results in tabular form

4. Next counter

The full True Basic program is shown below

! Centimetre Conversion! By A Teacher

CALL headingsCALL convert_and_print

SUB headings PRINT TAB(3);"Inches";TAB(12);"Centimetres"END SUB

SUB convert_and_print FOR inches = 0 to 50 step 5 LET cms = inches * 2.54 PRINT TAB(5);inches;TAB(15);cms NEXT inchesEND SUB

END

The output for this program is shown below in figure 7.2.

c _ HERIOT-WATT UNIVERSITY 2004

Figure 7.2:

Page 6: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

6

Note that the output of this program is in tabular form. This was achieved using the TAB function, first to output the heading then the results. TAB is short for tabulate and the output items are separated by the values within the tab statements.

If the value of step is not specified it is assumed by Visual Basic to be the value 1 by default.

Example 2: Displaying integers using negative stepProblem: Write a program that will output integers from 100 to 65 together with the corresponding characters that the ASCII numbers represent. Use a for..next loop with -ve step and output the results in tabular form.

Solution:1. Display the integers from 100 to 65

2. For counter = 100 to 65 step –1

3. Display the value of the integer and the character

4. Next counter

The True Basic Code is shown in code 2

!ASCII Converter! BY A Teacher

CALL headingsCALL display

SUB headings PRINT TAB(3);"Integer";TAB(15);"Character"END SUB

SUB display FOR counter = 100 to 65 step -1 LET char$ = CHR$(counter) PRINT TAB(7);counter;TAB(19);char$ NEXT counterEND SUB

END

A sample of the output is shown in Figure 7.3Note that, in this case the output has again been formatted using the TAB function. The program also uses the CHR$ function to convert a numerical value to its corresponding character.

For example: 65 returns the character "A"

c _ HERIOT-WATT UNIVERSITY 2004

Figue 7.3

Page 7: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

7

7.2.2 Nested For loops

FOR….NEXT loops can be nested to allow the programming of loops within loops.

Example 1: Use of nested loopsConsider the Tue Basic program coded below. See if you can visualise what the output will be before looking at the results screen:

!Nested Ifs!BY A Teacher

!This program will prompt a user to enter a number between 1 & 99!The program will test the number to see if it is less than 10!and print the message that it is a single digit number.!If it is > 9 it will print "double digit number"!otherwise "out of range"

INPUT PROMPT "Please enter a number between 1 and 99 ":testnumber

IF testnumber >=0 and testnumber <=99 then IF testnumber < 10 THEN PRINT testnumber;" is a single digit number" ELSE PRINT testnumber;" is a double-digit number" END IFELSE PRINT testnumber;" is out of range"END IF

END

This next program will illustrate nested loops.

!Nested For Next Loops!By A Teacher

!This program will illustrarte nested loops

FOR outer = 1 to 15 FOR inner = outer to 15 PRINT inner; NEXT inner PRINTNEXT outer

END

c _ HERIOT-WATT UNIVERSITY 2004

Page 8: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

8

In this program there are two loops controlled by the variables outer and inner.

The outer loop is initialised with the variable outer = 1. The inner, nested loop is now executed 15 times and the first line of numbers is printed on the same line. This is achieved by using the semi colon at the end of the first print statement. Outer thentakes on the value 2 and the process repeats itself until outer = 15 . Each time theoutput is decreased by 1 as the outer loop is executed until the value 15 is reached.

The print statement on its own ensures that a new line is taken for the next row of output. The print statement on its own basically means a line feed.

The output of the program is shown in Figure 7.4:

Note that it is considered bad programming practice to jump out of loops without terminating them fully. After the loops terminate the counter variables are discarded so if this is aborted prematurely, program output may not be as expected

c _ HERIOT-WATT UNIVERSITY 2004

For Outer

For Inner

Next Inner

Next Outer

Page 9: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

9

Experiment with the loops and range of numbers to arrive at different outputs.

c _ HERIOT-WATT UNIVERSITY 2004

Figure 7.4:

Page 10: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

10

Problem 2: Use of an If statement with nested For..Next loopProblem: Write a program that calculates bank interest on a sum of money that is input by the user. Output the capital sum together with the interest.Solution:Consider the following algorithm:

1. Ask user to input value2. If value <> 03. For count = 1 to 104. Calculate interest on value5. Output value and interest6. Next count7. Else output message “Value not valid – try again”8. End if

The True Basic code is shown below:

!Nested loops and IF!A Teacher

INPUT PROMPT "Please enter the capital ":capital

IF capital <> 0 THEN FOR counter = 1 to 10 LET interest = (capital * counter) / 100

PRINT "£";capital;" will gain £";interest;" at ";counter;"%" NEXT counterELSE PRINT capital;" is not a valid response - please try again"END IF

END

The program involves an IF statement with an embedded FOR…NEXT statement. If the capital sum does not meet the initial condition then control will be passed to the ELSE statement. If the condition is met then the program will continue and execute the FOR…NEXT statement and output the results as shown below.

c _ HERIOT-WATT UNIVERSITY 2004

Code and run the program

The output is rather poorly formatted. Greater control can be made using the PRINT USING commands. Investigate how you can improve the look of this so that it appears as:

£150 will gain £1.50 at 1%£150 will gain £3.00 at 2%and so on.

Page 11: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

11

ExerciseWrite a program that will output integer values representing the sides of right-angled triangles that satisfy Pythagoras's theorem i.e

a2 = b2 + c2

Only output values that satisfy the equation.

Hint You will require three nested FOR..NEXT loops and experiment with loop values upto 10 for each loop otherwise the program may run out of memory.

Drawing right angled triangles

Use a nested loop to draw right-angled triangle as shown below

Mowing Meadows

Use a nested loop to generate the following lines of a well-known verse:

1 man and a dog went to mow a meadow2 men, 1 man and a dog went to mow a meadow3 men, 2 men, 1 man and a dog went to mow a meadow….N men, N-1 men, N-2 men……, 1 man and a dog went to mow a meadow

For N=10

c _ HERIOT-WATT UNIVERSITY 2004

*************************

Page 12: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

12

7.2.3 Review Question

Q6: Which one of the following describes correctly an incremental for loop?

a) Control variable is decreasing in value by a variable amountb) Control loop variable is increasing in value by 1c) Control loop variable is increasing by a variable amountd) Control loop variable is increasing in value by a constant amount determined by the

programmer

Q7: Which one of the following statements is not permitted?

a) For loopCounter = (3*4) to (5*6) step 1b) For loopCounter = (3*4) to (5*1) step -1c) For loopCounter = (3*4) to (5*2) step 1d) For loopCounter = (3*4.16) to (5*5.6) step 1

Q8: Which one of the following problems is best suited to the use of a FOR loop?

a) Calculating the total number of marks entered at a keyboardb) As an event loop that checks for keyboard inputc) Calculating the average of marks held in a filed) All of the above

Q9: What shape will be displayed by the following Visual Basic program fragment forany value of N 1?

a) Triangleb) Squarec) Rectangled) Circle

Q10: What will be displayed by the following True Basic program fragment assuming N=3

LET sum = 0For I = 1 to N

For j = 1 to NLET sum = sum + j

Next jNext IPrint sum

a) 16b) 17c) 18d) 19

c _ HERIOT-WATT UNIVERSITY 2004

Page 13: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

13

7.3 Formatting output

Up to this point it has been left to True Basic to output data in default mode expect for a passing reference to PRINT USING.

Print Using allows you to format output data without using TAB statements and can make the lining up of headings and data very easy to do. A format string is required and this format determines the format of the output exactly.

For example if we want to output the following:-

Forename Surname Mark1 Mark2 Total James Taylor 23 45 68Etc.

Suitable formats would be:-

LET format1$ = “<############ <############### ##### ##### #####”LET format2$ = “<############ <############### ##### ##### #####”

Using < aligns to the leftUsing > aligns to the rightUsing no leading character aligns to the centre.

Suitable code using Print Using and these formats would be:-

PRINT USING format1$: Forename, Surname, Mark1, Mark2, TotalFOR i = 1 to 20

PRINT USING format2$: forename$(i), surname$(i), mark1(i), mark2(i), total(i)

NEXT i

The spaces between the format fields provide equal spacing between the columns of output.

Examples of other formats.

PRINT USING “-###.###” will give output like - 3.142 or 792.000PRINT USING “----#.###” will give output like –3.142PRINT USING “$$$#.###” will give output like $3.142 (it may work with £ depending on your set up)

There is a comprehensive treatment of this topic in the large True Basic manual. Meanwhile try and use PRINT USING to enhance the output in the short programs you are copying or writing yourself.

c _ HERIOT-WATT UNIVERSITY 2004

Page 14: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

14

7.4 Do Loops

With the FOR…NEXT loop the number of iterations must be known in advance so that the counter variable can be set.

There are many occasions in programming where the number of iterations is unknown so an alternative looping structure has to be used. The DO..LOOP is a viable alternative to the FOR…NEXT statement.

In True Basic, DO..LOOPs come in a variety of flavours and for any given program there will probably be more than one solution using a DO…LOOP variant.

There are two main constructs with two variants:

1 Do While….loop and variant Do Loop….While

2 Do Until….loop and variant Do Loop…Ultil

7.4.1 Do While..loop

The Do..While loop repeats a given set of instructions while a given condition is true. The general form of this statement is:

Do while test condition is true

Statements

Loop

The loop repeats itself until the condition becomes false. If the condition is false to begin with then the loop will not be entered and control will pass to the rest of the program.See Figure 7.6

While loops are used in situations where the number of times something has to be repeated is not known. They are often used in data validation where the user is repeatedly asked to enter values when invalid data is detected.

c _ HERIOT-WATT UNIVERSITY 2004

rest of program

Figure 7.6

Page 15: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

15

The Do...While loop is an example of a top tested while true structure. The variant doloop..while is an example of a bottom tested while true structure:

DoStatements

Loop while test condition is true

The top tested loop can iterate between 0 and N times whereas the bottom tested loop may iterate between 1 and N. This means that using the bottom-tested loop the iteration must occur at least once, so the condition can be tested immediately.

Care should be taken when writing programs using loops as an incorrect condition, or mistakes in the body of the loop can cause the program to get stuck in an infinite loop when executing, even when compilation produced no errors. Should this occur in True Basic make sure you are in the output window and click on File and Stop.

7.4.2 Examples of Do While.. Loop

Example 1 - Calculating a sum of positive integersProblem: A program is written to accept positive numbers from the keyboard, calculate and display a sum of all the numbers entered. It uses a do...while loop which tests whether each number entered is greater than or equal to zero. If the user enters a negative number then the loop will terminate and the total will be displayed on the screen.Solution:The algorithm is shown below:

1 set the running total to 0

2 display “Give me your first number

3 get number typed in at the keyboard

4 do while user’s number >=0

5 add 1 to the running total

6 display “Give me the next number”

7 get input typed in at the keyboard

8 loop

9 display the total

c _ HERIOT-WATT UNIVERSITY 2004

Page 16: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

16

The True Basic code is shown below:

!This program will illustrate the do while loop!This program will add a list of positive numbers typed in at the keyboard.!The program will stop when a negative number is entered!and display the total

LET total = 0INPUT prompt "Give me your first number ":inumberDO while inumber >= 0 LET total = total + inumber INPUT prompt "Give me your next number ":inumber PRINT "Your numbers add up to ";totalLOOP

END

Example 2 – Validating Character Input Problem:

A program is written to prompt the user to enter a character. The program continues to prompt until it receives a character other than a “Y” or “y”.

Solution

The algorithm is shown below:

1 Display “Continue”2 get input from keyboard3 do while user enters “Y” or user enters “y”4 display “Continue”5 get input from keyboard6 loop7 display “Out of loop”

c _ HERIOT-WATT UNIVERSITY 2004

Page 17: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

17

! Do while loops!Continue

PRINT "Continue"INPUT prompt "Please enter a character ":char$PRINT char$DO while char$ = "Y" or char$ = "y" PRINT "Continue" INPUT prompt "Please enter a character ":char$LOOPPRINT "Out of loop"END

The program output is minimal; since it only responds to the correct input then the program will simply accept the character that is entered. Only when the incorrect character is entered will the program fail to enter the loop and come up with the message "Out of loop".

This code can be used as part of a larger program to validate input. If coded as a procedure then it can be called from within the main program. We will discuss procedures more fully later in the final topic.

Example - Range checking using a boolean variableProblem: A program is written to ask the user to enter a value. If the value is outside the range expected the user will be prompted to enter another value. This is another example of validation, only in this program the use of a boolean variable is exemplified.

Solution:The algorithm is shown below.

1 input “What size is needed”2 set value of OK to false3 do while OK = false4 if (size >= low value) and (size <= high value) then5 set OK to true6 display “This size in range”7 else8 display “This size is out of range”9 display “try entering another size10 input “what size is needed?”11 end if12 loop13 display “out of loop”

c _ HERIOT-WATT UNIVERSITY 2004

Program output

Page 18: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

18

The True Basic code for this program.

!Program Rangecheck!This program prompts the user to enter a numeric value.!It uses a while loop to repeatedly check that a value!is between lowvalue and highvalue

LET lowvalue = 10LET highvalue = 20

LET true = -1INPUT prompt "Wahat size is required ":sizeDO while true =-1 IF size >= lowvalue and size <= highvalue then LET true = 0 PRINT size;" is in range" ELSE PRINT size;" is out of range - try again" INPUT prompt "What size is required ":size END IFLOOPPRINT "Out of loop"

END

Type in the program and run it with some sensible test data. You should test out of range above and below, on the limits and in range.

Q11: What is wrong with the following?n = 0 “assume n is an integer”do while n < 100

value = n*nloop

Q12: What is wrong with the following?i = 1 “assume i is an integer”do while i <=10

print ilet = i + 1

Q13: Write a loop that calculates the sum of all numbers between 0 and 20 inclusive. Hint: use two integer variables, one for a loop counter and one for keeping a running total of the numbers

c _ HERIOT-WATT UNIVERSITY 2004

Page 19: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

19

7.4.3 Do Until..Loop

The while...do loop performs the conditional test first and then executes the loop, sothe statements within a loop may never be executed. The do until loop performs the statements first and then tests the condition. This means that the body of the loop is always executed at least once. This is the only difference, but a significant one between these looping constructs.

rest of programFigure 7.9

The general form of a do until...loop is:

Do until test conditionStatements

loop

The statements in the body of the loop are executed repeatedly until the test condition is FALSE.

See Figure 7.9

The do until...loop is an example of a top tested while false structure. The variant do loop...until is an example of a bottom tested while false structure:

DoStatements

Loop until condition is true

The top tested loop can iterate between 0 and N times whereas the bottom tested loop may iterate between 1 and N. This means that using the bottom tested loop the iteration must occur at least once, so the condition can be tested immediately.

c _ HERIOT-WATT UNIVERSITY 2004

Page 20: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

20

Some simple examples should clarify the situation.

Consider the simple lines of code representing a simple do until...loop

Let num = 0Do Until num = 10

Let num = num + 1LoopPrint num

The equivalent do while...loop would be

Let num = 0Do while num < 10

Let num = num + 1LoopPrint num

Although both loops end up with similar results their methods are different. With the do until...loop the condition num = 10 is set and the loop must be entered at least once to test this condition as is continually tested until the condition fails i.e. Num becomes > 10 and the loop exits with Num = 10

The equivalent do...while loop tests the condition in the first line and if false the loop will not be entered. If true then the loop will run until num = 10 when the loop exits.

When should you use one and when the other? If you know it is safe to run the code at least once, probably you should use the do...until loop. If you must run the code at least once then again a do...until loop is a good solution. If there is any reason to doubt the value of any variables etc. in the loop, then you should always use the do...while loop. Menus often use do...until loops, as you know that the menu needs to be run at least once for the user to see it!

A number of worked solutions to problems are given here - make sure you understand what is going on in these examples. You may wish to try running these programs for yourself and to experiment with making changes to the code to ensure you fully understand what is happening.

Example 1: Guessing an age with do...until and nested if...else statement

Problem: A program is written to ask the user guess an age, the value of which is stored as a program constant. The program counts the number of tries needed to guess the correct age and declares whether the guesses are high or low.

Solution:The algorithm is shown below:

Set the number of guesses to 01. Do3 Request an age from the user4 If guess > age then output message5 Else6 If guess < age output message7 Add 1 to the number of gueses8 Loop until guess = age9 Display t”the number of times guessed”

c _ HERIOT-WATT UNIVERSITY 2004

Page 21: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

21

The True Basic program is shown below

! My age

LET myage = 21 !againLET guesses = 0

DO INPUT prompt "Guess my age ":thisguess LET guesses = guesses + 1 IF thisguess < myage then PRINT "This guess is too low" ELSEIF thisguess > myage then PRINT "This guess is too high" END IFLOOP until thisguess = myage

PRINT "OK so my age is ";myage;" but it took you ";guesses;" to guess it"END

Enter and run the program yourself and check the output.

You may wonder why the ELSEIF statement is used, since by default if thisguess < myage is false then thisguess must be true within the IF…ENDIF statement. This is so but when the initial condition is met myage = thisguess an error occurs stating that the value 21 is too low followed by the correct statement as the loop exits.

Example 2: Use of two do until loops to output a number series like Fibonacci numbers and to validate the input.

Problem: Write a program to output numbers belonging to the Fibonacci series up to a specified maximum.

Solution: Fibonacci was a famous Italian mathematician who identified the following series of numbers:

1, 1, 2, 3, 5, 8, 13……

Successive terms of the series are calculated by adding the previous two numbers. The following algorithm will produce the series, given the first two values as input.

1 Do2 Input number of terms to output3 Loop until input is within range4 Input two starting values5 DO6 Compute numbers7 Display numbers8 Loop until number of terms have been output

c _ HERIOT-WATT UNIVERSITY 2004

Page 22: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

22

The program is shown below

! Fibonacci Sequence! Terms restricted to between >0 and < 15

DO INPUT prompt " How many terms to display ":noofterms !validation checkLOOP until noofterms > 0 and noofterms <=16

INPUT Prompt "Enter first number ":firstINPUT prompt "Enter second number ":secondLET third = 0LET count = 0

DO LET third = first + second LET first = third LET second = third + second PRINT first;" ";second; LET count = count + 1LOOP until count = (noofterms - 2) / 2

END

And a sample of the output is:

The program input is restricted to values > 0 and<=15 otherwise the do until loop will never terminate until a value within the range is input.

If you find difficulty in following the logic of the program then perform a paper exercise running through the values of each variable as the program executes. This is called a dry run and is best done by means of a trace table:

Instructions First Second Third Output

StartingValues

1 1

First Loop 2 3 2 1 , 1

Second Loop 5 8 5 2, 3

Third Loop 13 21 13 5, 8

c _ HERIOT-WATT UNIVERSITY 2004

Page 23: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

23

The two starting values are 1 and 1 which are assigned to variables first and second. Variable third then takes on the value of first + second which is 2. First now takes on the value of third to become 2. Finally the variable second takes on the value of third + second to become 3. The values of first and second are now displayed to give the output:

1, 2, 3, 3, 5, 8, 13, 21, 34, 55

Because the output is first and second the value of count is halved otherwise the output would be twice that required i.e.

Do until count = (noofterms – 2) / 2

Also the value of noofterms is decreased by 2 to take into account the first two values which are output and are not part of the loop.

c _ HERIOT-WATT UNIVERSITY 2004

Page 24: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

24

7.4.4 Review Questions

Q14: Which one of the following statements is true regarding the do while loop?

a) The conditional statement is always satisfiedb) The block of code is entered first before the condition is tested c) The loop need not be entered if the condition fails at the start d) The loop terminates when the condition becomes true

Q15: Looping structures have several features in common. Which one of the following is NOT one of these features?a) Selection b) Increment c) Initialisation d) Condition

Q16: What is the output of the following program fragment that uses a do while loop?Let i = 0Do

Let i = i + 1Print i;

Loop while i< 8a) 0 1 2 3 4 b) 1 2 3 4 5 c) 0 1 2 3 4 5 d) 1 2 3 4 5 6

Q17: In the previous example the do while loop is replaced by a do until loop as follows:

Let i= 0Do

Let i= i + 1Print i;

Loop until i< 5

a) 0b) 1c) 0 1 2 3 4 5 d) 1 2 3 4 5

Q18: What can be done to make the output of the program fragment in (3) the same as the program fragment in (2)?

a) Change last statement to Loop Until NOT i < 5b)c)d)

Change last statement to Loop Until i >5Use a for loop with counter variable iAny one of the above

c _ HERIOT-WATT UNIVERSITY 2004

Page 25: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

25

7.4.5 Programming Exercises

In the following exercise please write the algorithm first and then code the program.

Set 1 – Control Structures – Sequence

1. Write a program which displays a message asking for a number, gets a number from the keyboard and then displays the number on the monitor.

2. Write a program which displays a message asking for your name, gets name from the keyboard and then displays it on the monitor.

3. Write a program to add 2 numbers as follows: display a message asking for a number and get a number from the keyboard store it in number1, do this again to get the second number store it in number2 , then add the numbers together store the answer in a variable called answer and display answer on the monitor.

4. Write a program to add 3 numbers as follows: display a message asking for a number and get a number from the keyboard, do this another twice to get the other numbers, then add the numbers together store the answer in a variable called answer and display the answer on the monitor.

5. Write a program which inputs 3 numbers from the keyboard and stores them in an array called numbers. The sum of the 3 numbers should be calculated, stored in a variable sum, then displayed on screen.

Set 2 – Control Structure 2 – Selection

1. Write a program which will store the value 8 in a variable called secret_number, then ask for and get a number from the keyboard. If the number is less than secret_number, the message "Too Low" should be displayed, if the number is greater than secret_number, the message "Too High" should be displayed, and if the number is equal to secret_number then the message "You have found the secret number " should be displayed.

2. Write a program which will store a word of your own choosing in password. The program should then display a message asking for, and getting a word from the keyboard. If the word is the same as password , then the message "The password is correct" should be displayed else the message "The password is wrong" should be displayed.

3. Write a program which will accept a character entered at the keyboard. If the character is M or m then 1 should be added to a variable no_of_boys. If the character entered is F or f then 1 should be added to a variable no_of_girls.

c _ HERIOT-WATT UNIVERSITY 2004

Page 26: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

26

Set 3 – Control Structure 3 – Repetition

1. Write a program for a program which will display a piece of text 100 times. Use a fixed loop in which the counter goes from 1 to 100.

2. Write a program which will display a list of the even numbers from 2 to 20.

3. Write a program which asks the user to input a sentence and store it in a string variable, and then check each letter to see whether it is a capital letter, space or full stop. If it is then no action is taken but any character which fails the test should be displayed with a suitable message and a warning sound made. This program should be saved as you may need to use it as a subroutine in a later program or assessment.

4. Write a program using a DO ( Repeat ) loop to repeat a section of program which will get a number , display the number and keep asking for more numbers until the number 0 is entered.

5. Write a program, using a DO (Repeat ) loop, which will get a name , display the name and keep asking for more names until STOP is the name entered.

6. Write a program which sets a total to 0, then repeats a section of program which asks for numbers, one at a time, each to be added to the total, until 0 is entered. When 0 is entered the program should finish by displaying the message "The total of the numbers is " followed by the actual total.

7. Rewrite the program for Question 1 using a different loop structure

8. Rewrite the program for Question 2 using a different loop structure

9. Rewrite the program for Question 3 using a different loop structure

10. Rewrite the program for Question 4 using a different loop structure

11. Rewrite the program for Question 5 using a different loop structure

c _ HERIOT-WATT UNIVERSITY 2004

Page 27: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

27

7.5 Arrays

In the exercises so far you have looked at simple data types, such as single(real) and integer. The next thing we want to look at is how related data items can be stored together using arrays. In this topic we will investigate:

1. the requirement for arrays

2. array declaration

Much of this material may be familiar to you already. However, it is necessary gain more practice in the use of arrays in order to better prepare you for a later topic on standard algorithms which makes extensive use of this type of data structure.

A data structure is a way of storing data in a computer in an organised way. One of the simplest data structures used in computer programming is called an array and is an example of a static data structure because it is of a fixed size within memory as defined within the structure of the program.

An array is a list of data items such that each item is uniquely identified by its position in the list. Also, an array is given a name, which is usually related to the group of data it holds. Some examples might be:

Data Items Array Name

Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,Saturday

'Days of the week'

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F 'Hexadecimal digits'

£1, £2, 50p, 20p, 10p, 5p, 2p, 1 p 'Decimal coinage'

1-Dimensional arrayAlso called a Linear List the data items are simply stored in consecutive locations within a block of computer memory as follows:

Thus the data item 'Tuesday' is stored in array location Days of the week(2) and thedata item 'Saturday' as . Days of the week(6). Each data item therefore is uniquelyidentified as an index or subscript.

Note that the index values are not actual memory addresses as such but simply refer to the data positions within the array.

c _ HERIOT-WATT UNIVERSITY 2004

Page 28: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

28

Imagine you were to process the average temperature data in Edinburgh for the last 30 days. If each of the day's temperatures is stored as a separate variable you would require 30 distinct variables, and the storage and manipulation of these variables becomes difficult.

To overcome the above problem, you can define a variable called temperature which represents not a single temperature but an entire set of temperatures.

This is illustrated in Figure 7.12 showing an array structure called temperature and elements with the subscript ranging from 1 to 8.

1 2 3 4 5 6 7 8

Figure 7.12: Representation of an array and indices

An individual array element can be used anywhere that a normal variable could be. i.e.

Temp = temperature(27)Average = (temperature(5) + temperature(6))/2.0

A value can be stored in an array simply by specifying the array element on the left hand side of the assignment operator (equals sign), e.g.

LET temperature(2) = 18.0

Assigns the value 18.0 to be stored in element with subscript 2 of the temperature array.

LET temperature(7) = 14.5

Assigns the value 14.5 to be stored in element with subscript 7 of the temperature array.

This is illustrated in Figure 7.13

18

14.5

1 2 3 4 5 6 7 8

More generally, an integer variable can be declared and used as the subscript, e.g

LET temp = temperature(i)

c _ HERIOT-WATT UNIVERSITY 2004

Temperature(1) Temperature(6)

Index or subscript

temperature

Index or subscript

Page 29: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

29

Which will take the value assigned in element number I of the array temperature and assign it to the variable temp.

This means that if you want to access the elements of an array sequentially, you can do it using a loop where the variable for the subscript is automatically incremented each time you go round the loop. Remember that the subscript variable can only be an integer. A real (e.g decimal) number is not allowed. The examples within this topic will show you how you can access an array using a loop. This is the most common way of marching through an array from beginning to end, and as you will probably use this technique a lot in your programs.

7.5.1 Declaring arrays

Before you can use an array it must be declared at the beginning of the program with the other variable declarations. The declaration provides the name of the array, the number of elements and the data type of the elements.

Like variables arrays can be declared using the True Basic keyword DIM or DIMENSION (we usually use DIM) Arrays can dimensioned as either numeric or string arrays.

e.g DIM temperature(8) is a numeric array

while DIM name$(10) is a string array and sets up space for 10 names.

Note that in True Basic, when an array is declared the first element of the array is 1 (one).

ErrorsNote that you cannot mix array types. Once they have been declared as type then they cannot be used to store integer, real or string variables together. Arrays can be quite tricky and you will probably receive quite a few error messages that only occur at run time.

The most common error is to attempt to access an array element outwith the declared bounds e.g. accessing element 0, or 15 of an array with subscript range specified as 10.This type of error is so common that it has been given the name ̀ fencepost error'. It is not a minor error as it can crash the system. If an array has an upper bound of [9] and you attempt to write something to item [10] then you could well be overwriting some variables that the computer has put in that location. You may be lucky and there is nothing important there. You may be unlucky. It does not matter whether your program works or not, it is flawed and incorrect. Sooner or later it will fail. True Basic traps this error and reports it to the user at run-time.

7.5.2 Initialising arrays

In computer programming arrays are used to manipulate data and the actions include:

initializing the array reading data into the array searching the array for data items sorting data items

For this topic we will focus on the first three only.

c _ HERIOT-WATT UNIVERSITY 2004

Page 30: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

30

Initialising an array simply means setting all the array elements to zero, null or a specified value.

Suppose we have an integer array called Numbers that can hold 6 values. To set all the locations to zero we can use the following statements:

To initialise an array of, say 1000 data elements this would be a very impractical way of doing it.

A much shorter method would be to use a loop structure as in the following piece of code:

LET index = 1 !initialisingDO UNTIL index = 1000

LET number(index) = 0LET index = index + 1

LOOP

Initialisation is also useful to clear arrays of old data which otherwise might corrupt the new data being processed.

Whereas initialisation sets all array elements to be identical the same method can be used to input data. For example to read the days of the week into the array called Days: :

LET index = 1 !initialisingDO UNTIL index = 7

INPUT days(index) LET index = index + 1

LOOP

The following days would be input one by one into the array

“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”

In this case when Index takes the value 1 the first data item - Sunday - will be read in to the array element Days(1). Index then takes the value 2 and the process repeats itself until all the data has been entered.

c _ HERIOT-WATT UNIVERSITY 2004

Page 31: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

31

7.5.3 Examples of using arrays

Example 1 - Using an integer variable to access an arrayProblem: How can the array temperature be initialised to zero using a for loop? Solution: A typical solution to this problem is shown here.

FOR count = 1 to 5LET temperature(count) = 0

NEXT count

The first time round the loop the variable count has the value 0 and so the element with index number 0 of the array temperature is set to 0. The next time round the loop count has been incremented by 1 and has the value 1 and so element index number 1 of the array will be set to 0 and so on.

This one simple loop replaces 5 lines of code e.g.

LET temperature(1) = 0LET temperature(2) = 0LET temperature(3) = 0LET temperature(4) = 0LET temperature(5) = 0

Example 2 - Writing out the contents of an arrayProblem: How can the contents of an array be displayed using a loop?

Solution: If you assume you have an array called Store, which has 6 elements, then you could use the following code to display the contents of each element.

FOR count = 1 to 6PRINT “element ”;count;” = “;store(count)

NEXT count

For example, if the array Store held the values (3, 12, -4.6, 3.2, 0, -1), see Figure 7.14, then the information displayed would be

Figure 7.14: Contents of a six-element array Store- Generic and not True BASIC

c _ HERIOT-WATT UNIVERSITY 2004

Page 32: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

32

This time one simple loop replaces 6 lines of code, i.e.

PRINT “element 1 = “;store(1)PRINT “element 2 = “;store(2)PRINT “element 3 = “;store(3)PRINT “element 4 = “;store(4)PRINT “element 5 = “;store(5)PRINT “element 6 = “;store(6)

Look carefully, and you can see that the array can only be written out element by element.You cannot use one statement to print the entire array. For example, it is wrong to say:

PRINT store

and expect all elements of the array to be displayed.

A single element can be written or accessed at random - you are not forced to process the entire array to do this! Any one of the six lines of code above does the job of printing out that particular array element, so the code PRINT “element 5 = “;store(5) outputs the fifth element of the array - the first element being element 1.

Example 3 - Reading user input into an arrayProblem: How can data entered by the user at the keyboard be stored directly into the elements of an array?Solution: Consider the situation where you want to store 4 user entered integers in an array called mark. You could use a for next loop to prompt and obtain input and to store the integers in the array, i.e.

FOR times = 1 to 4INPUT PROMPT “Please enter a mark “:mark(times)

NEXT times

For each loop the user will be asked to input a mark. After four marks have been entered the loop will terminate and the array mark will be storing the four values.

Using arrays

Several examples using arrays have been illustrated in the course notes. Incorporate these program fragments into a working program which can do three things:

1. initialise each element of an array to hold 5 numbers, to zero;2. allow you to input data in the form of real numbers directly into the array; 3. print out the contents of the array.

Try to make the program user-friendly by putting relevant information on the screen.

Finally, add a section to the above program which will print the array in reverse order after it has printed it conventionally.

c _ HERIOT-WATT UNIVERSITY 2004

Page 33: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

33

Indexing arrays

Learning Objective

To understand how the index numbers are used in arrays. If you have access to the Scholar Web Site then an online array interaction is available to help you. If not then you can still answer the questions on paper.

Q19: Begin with an array of 4 elements with a subscript range of 0..3. All values are initialised to 0, i.e. array = [0, 0, 0, 0]. Set array[1] = 3. What are the arrays contents now?

a) array = [0, 0, 0, 0]b) array = [3, 0, 0, 0] c) array = [0, 3, 0, 0] d) array = [0, 0, 3, 0] e) array = [0, 0, 0, 3] f) none of the above

Q20: Using the same array set array[0] = 7. What are the array contents now?

a) Array= [0, 0, 0, 0]b) Array= [3, 7, 0, 0]c) Array= [3, 0, 7, 0]d) Array= [7, 3, 0, 0]e) Array= [0, 3, 7, 0]f) Array= [7, 0, 3, 0]g) Array= [0, 7, 3, 0]h) Array= [0, 7, 0, 3]j) Array= [0, 0, 7, 3]

Q21: Set up a 4 element array with a subscript range of 0..3 with the following values: array = [3, 6, 2, 8]. What is the value of array[2]?

a) 3b) b) 6 c) 2 d) 8e) none of the above

Q22: In the same array as the previous question, what is the value of the element with index 0?a) 3b) 6 c) 2 d) 8e) none of the above

c _ HERIOT-WATT UNIVERSITY 2004

Page 34: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

34

Q23: Set up an 8 element array with a subscript range of 0..7, i.e. array = [8, 23, 5, 19, 3, 0, 7, 52]. Now set array[1] = 12. What are the array contents now?

a) array = [8, 23, 5, 19, 3, 0, 7, 52] b) array = [12, 23, 5, 19, 3, 0, 7, 52] c) array = [8, 12, 5, 19, 3, 0, 7, 52] d) array = [8, 23, 12, 19, 3, 0, 7, 52]e) array = [8, 23, 5, 12, 3, 0, 7, 52] f) array = [8, 23, 5, 19, 12, 0, 7, 52] g) array = [8, 23, 5, 19, 3, 12, 7, 52] h) array = [8, 23, 5, 19, 3, 0, 12, 52] i) array = [8, 23, 5, 19, 3, 0, 7, 12] j) none of the above

Q24: Again, starting with an 8 element array with a subscript range of 0..7 i.e. array[8, 23, 5, 19, 3, 0, 7, 52]. Set array[3] = 9, element with index 6 = 11 and array[6] = 4. What are the array contents now?

a) array = [8,23,5,9,3,0,4,52]b) array = [8,23,5,19,9,4,7,52]c)array = [8,23,5,9,3,4,7,52]d) array = [8,23,5,19,9,4,4,52]e) none of the above

Q25: Set up an array that can hold 4 values with a subscript range of 0..3. Initialise the array to hold all 0 values. Now set the following values:

array[1] = 9 array[2] = 3

What are the contents of the array now? (express in format of array = [3, 2, 5, 0]).

Q26: Set up an array that can hold 10 values with a subscript range of 0..9 Initialise the array to hold all 0 values. Now set the following values:

array[4] = 6 array[8] = 2 array[1] = 7 array[7] = 3

What are the contents of the array now? (express in format of array = [3, 2, 5, 0]).

Q27: Write a program that will set each element in an array, called myarray, of 10 elements to the value of its index. The contents of the array are then printed out in a vertical line

What are the contents of myarray now? (express in format of myarray = [3, 2, 5, 0]).

c _ HERIOT-WATT UNIVERSITY 2004

Page 35: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

35

7.5.4 Review Questions

Q28: Initialising a 1-dimensional array means:

a) Setting all locations of an integer array to 0 (zero)

b) Setting all locations of a string array to nullc) Setting all locations of a real array to pre-determined values d) All of the above options

Q29: The contents of a string array message() contain the following characters in successive memory locations:

H A P P Y B I R T H D A YThe programming structure required to produce the above message could best be achieved using: (choose one)

a) A case statement b) A for loop c) A while loop d) An until loop

Q30: An array is declared with 6 elements and initialised to contain the following values:

0 3 0 2 5 9

During a program run the array elements are changed as follows:

Numbers(2) = 6Numbers((5) = 7Numbers(1) = 4

The array contents are now:0 3 0 2 5 94 3 0 2 5 9 4 6 0 2 7 0 0 4 6 2 5 7

Q31: An array, value_1(), has been dimensioned in True Basic to hold 5 values. Which one of the following statements would produce an error when the program is run?a) value_1(0) = "Hello"

b) value_1(6) = 89.45c) value_1(1) = 5.6E37d) value_1(2) = 16

c _ HERIOT-WATT UNIVERSITY 2004

Page 36: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

36

7.5.5 Worked example programsA number of worked solutions to problems are given here - make sure you understand what is going on in these examples. Run these programs for yourself and experiment with making changes to the code to ensure you understand what is happening. It is important that you do this - programming is a skill, which is learned by doing. Just reading the examples will not give you that skill.

Since some of the programs can be quite complex they are dealt with in meaningful chunks and more of this will be dealt with later.

Example 1 - Calculating the average temperatureProblem: Write a program to access each of the temperatures of a room over 14 days, which are to be held in an array. Calculate the average temperature during the period. No display of the results is required, but that of the final average is.

Solution: First try: A typical solution to this problem is shown in the code below.

! Calculate Average Temperature

DIM store(14)

LET total = 0 !initialise total

! Program now puts the values into the Store ArrayFOR day = 1 to 14 PRINT "Please enter the temperature for day ";day; INPUT store(day) LET total = total + store(day)NEXT day

LET average = total /14PRINT "The average temperature was ";average

END

The program above asks the user to input values each time the program is run. There are other input methods which could be used, such as reading a file, or downloading the information from a remote monitor, but we will stick to the straightforward method at the moment.

Try and improve the appearance of the input and output using a format.

c _ HERIOT-WATT UNIVERSITY 2004

Page 37: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

37

Simulations

Using arrays makes it easy to simulate many numerical activities that otherwise would be fairly tedious to do manually. For example analysing the results of tossing a coin 1000 times, throwing die or spinning a roulette wheel can all be dealt with in one-dimensional arrays. Such simulations make use of random numbers that can be generated between upper and lower limits for example:

tossing a coin: random values 1 (for heads) or 2 (for tails) throwing

a die: random values between 1 and 6 roulette: random values

between 0 and 49.

Random numbers

True Basic has a function that produces a random number from 0 to 1. The RND function requires no arguments and each time the RND function is invoked a new number is returned. Random numbers are generated internally using the computer's internal clock. To facilitate debugging True Basic produces the same sequence of pseudo random numbers each time it is run. However you probably want a different set each time to produce a truly random series of numbers and to achieve this, the RANDOMIZE statement is inserted near the beginning of your program or subroutine.

Another useful function is INT which returns the greatest integer that is less than or equal to its argument. For instance INT (2.34) returns 2. Values are always rounded down when using Int. Int can be used to with RND to generate random numbers in different ranges. E.g.

LET coin = int(2*rnd) + 1 - will give a value of 1 or 2 to coinAndLET die int(6*RND) + 1 - will produce a range of random numbers between 1 and 6.

Example 2: Simulation of throwing a coinProblem: Write a program to simulate the tossing of a coin up to1000 times determined by the user and output the number of heads and tails produced.The program can be done in several sections:

1. Generate random numbers within the range 2. Store results of up to 1000 tosses 3. Display output

The following code segment will generate the random numbers and convert them to integers within the range 1 and 2 and store them in an array called headstails.

RANDOMIZEFor throw = 1 to 1000LET headstails(throw) = int(2*rnd) + 1NEXT throw

This will fill the array headstails with 1s and 2s.

c _ HERIOT-WATT UNIVERSITY 2004

Page 38: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

38

Counting heads and tails

With 1000 numbers stored we can now scan the array and count the occurrences of 1's and 2s that represent heads and tails.

The following code segment should accomplish this:

FOR throw = 1 to 1000If headstails(throw) = 1 then

Let heads = heads + 1Else

Let tails = tails + 1End if

Next throw

Finally you can code the output section to display the number of heads and tails.

What would you expect the values to be and why?

Code the program and run it several times to see if you are correct.

The program can easily be modified to simulate throwing a die.

Exercise

Amend the program you have just written to output the results of throwing a die about 60 times. Statistically you should get around 10 of each of the numbers 1 to 6. Count the number of 6s in a set of throws and your output should show the number of 6s. Change the number of times you “throw the die” to 600, then 6000 and so on and see if the results are more evenly distributed as the repetitions get higher.

3 -Testing for Palindromes using an arrayProblem: Write a program which will read in a sequence of words. The characters will be read into an array and the program should then determine if the sequence is a palindrome.

Note: A palindrome is a sequence of number/characters/words etc. which is the same when read from either direction.

The following examples are palindromes, the sequence being the same when read from left to right or from right to left.

2 3 4 5 4 3 2

madam im adam

mas not a ton sam

a man a plan a canal panama

eve

This program may seem more complicated than it really is. If you follow the explanation you will see that by breaking it down into small steps, each of which can be written in True Basic you will chip away at the problem until it is done.

c _ HERIOT-WATT UNIVERSITY 2004

Page 39: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

39

The solution to this problem assumes that you do not know how many words are going to be input.

SolutionThe program does not know how big a sequence will be entered so an array of characters larger than required is declared. The program reads in the sequence of characters one at a time into the array, terminated by a full stop. It also checks that the array bounds are not breached by testing the condition:

Count <= size

Using a do…while loop

This is important; otherwise an array bounds error will likely occur. The constant. Size is initially set to 30 but may be altered if large strings are used.

The condition in the while…do loop loop that checks whether "." was the last character entered is

Palidromechar$ <> “.” <> Means not equal to.

Once it has completed reading in the characters, you can determine the number of values read in. This is count – 1 not count since you are not interested in the last character. All it contains is the "." termination character which you do not want to use in the rest of the program.

Now you are ready to see whether the string is a palindrome. The array is searched through comparing the 1st element with the last, the 2nd element with the 2nd last etc. As soon as you find that they do not match you can terminate the search, as you know that the sequence is not a palindrome. It is not necessary to continue searching the whole list of characters, as we know what we set out to find out.

Note that you only have to loop for count <= length as you compare the first half of the array to the second half. See following Figure 7.17:

Figure 7.17: Comparing array elements for a palindrome

c _ HERIOT-WATT UNIVERSITY 2004

length - 1 length0 1 2 3

Page 40: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

40

A possible solution is shown in the code below

! Palindromes

!this program will test an input string for a palindromeLET sizearray = 30DIM palarray$(30)

LET count = 1

PRINT "Please enter your characters, one at a time. Terminate with . "DO while (palindromechar$ <> ".") and (count <= sizearray) INPUT palindromechar$ LET palarray$(count) = palindromechar$ LET count = count + 1LOOP

LET length = count - 1 !to account for incement when "." is input

!Now check for palindrome

LET ispalindrome = 0LET count = 1DO while (ispalindrome = 0) and (count <= length / 2) IF palarray$(count) <> palarray$(length - count) then LET ispalindrome = 1 ELSE LET count = count + 1 END IFLOOP

IF ispalindrome = 0 then PRINT " is a palindrome"ELSE PRINT " is not a palindrome"END IF

END

Examine the do…while statements very carefully. You will see that the conditions are compound.

You could use string and substring handling routines to actually capture the word or phrase so that it can be used to make the output more meaningful. Try and amend your program to do this.

The character read in must not be a full stop and there must still be space left in the array if both these conditions are fulfilled, then the loop continues if either one or the other condition fails, then the loop terminates.

The do…while (ispalindrome) and (count <= length / 2) statement tests whetheryou have gone halfway through the array AND whether the boolean variable ispalindrome has been set to false.

This needs a bit more explanation:

c _ HERIOT-WATT UNIVERSITY 2004

Page 41: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

41

notice that we initialized ispalindrome to 0 at the beginning of the program. I f you look at the output statements right at the bottom of the code, you can see that if

ispalindrome is still true, then the array is a palindrome if ispalindrome as been set to false at any point, then the array is not a palindrome this is what a boolean flag is for. You set it to a state - here it is either true or false and you

use this value to see whether a certain condition still holds true so what might set ispalindrome to false? It is the code inside the while...do loop which compares the first and last items if they are not the same, the boolean flag is set to false. Otherwise nothing happens then the second, and second from last are compared. ….and so on.

In terms of loop tests this is probably about as complicated as it gets. If you do not understand it this time around, just be patient - you will probably find that you need to code something like this yourself in the future and you can come back to this example. By actually doing it, the difficulties seem much less than by reading it as you are doing now.

There are other methods, probably much simpler, of writing programs to test for palindromes. However it is essential that you understand the use of arrays since they are important data structures in all fields of computing. You will see more in the use of arrays in the final topic.

Comparing arrays and encoding the results

Declare three 20-element arrays, X, Y, Z. Write a program to read 20 integers into each of the two integer arrays X and Y. The program will prompt the user to enter the values into each of the arrays. The program will then compare each of the elements of X to the corresponding element in Y. Then, in the corresponding element of a third array Z store the following values, Table 7.2.

Table 7.2:Z Element

ValueCondition

1 if the element in x is larger than the element in y

0 if the element in x is equal to the element in y

-1 if the element in x is less than the element in y

Then print out a three column table displaying the contents of the arrays X, Y and Z. M ake up your own test data and write down in three columns the number you input for X, the number you input for Y and the result you got for Z

c _ HERIOT-WATT UNIVERSITY 2004

Page 42: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

42

Comparing arrays - extensionIf you found the previous exercise absurdly easy, then you can follow up with this one.

Extend the above program by adding two further columns to the output giving each line five columns. This is what you add: (column 4) a count of the number of elements of X that exceed Y and (column 5) a count of the number of elements of X that are less than Y.

7.6 Summary

The following summary points are related to the learning objectives in the topic introduction: understand and be able to use the 'for ..next' structure;

understand and be able to use the 'do..while' structure and variant;

understand and be able to use the do..until structure and variant;

how to declare 1-D arrays;

initialise a 1-D array;

manipulate data held in 1-D arrays.

7.7 End of topic test

An online assessment is provided to help you review this topic.

c _ HERIOT-WATT UNIVERSITY 2004

Page 43: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

43

EXERCISES : Manipulating Data Structures (arrays)

Programs

1. Produce a program to store 10 names of your choice in a string array and on the input of a number between 1 and 10 print out the name in that element of the array. The program should then loop back for another number or terminate when 0 is entered.

2. Write a program to store the following numbers in an array then find and print out the largest number by scanning through the array. The numbers are 5,8,13,12,9,2,20,18,11,8,14,25,7,1

3. Rewrite Q2 to find and print out the smallest number.

4. Rewrite Q2 to find and print out the number of times 8 appears in the list of numbers.

5. Produce program which will input up to 30 positive numbers then find and print out in an informative display:-

the average of the numbersthe largest numberthe smallest number

The program should then allow the user to enter a number likely to be in the list. It should then find and display the number of times it occurs in the list.This should be repeated until -1 is entered as a terminator to end the program.

c _ HERIOT-WATT UNIVERSITY 2004

Page 44: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

* * * * * * * * **

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * *

*********************************************

44

EXTENSION EXERCISES

1. Write an algorithm and program which will print out the position of a letter of the alphabet, i.e. if B or b is entered then 2 should be printed out.

2. Write an algorithm and program which should input your name one letter at a time. It should then take each letter and code it using a simple calculation of your own choice. The output of the coded name should be in lower case letters only in the following form:4 letters 2 spaces 4 letters 2 spaces until all letters are usedHint: Each letter should be stored in an array. Example of a simple code find ASCII add 5. What would you do with letters v,w,x,y and z?

3. Produce an algorithm and program which will on the input of 28, 29, 30 or 31 print out the name of the month(s) which have these number of days in their months, or print out a message saying that there is no month with the number of days, if a value other than 28 to 31 is input.

4. Produce an algorithm and program that will on the input of up to 3 characters print out the appropriate name of the month. The program should be able to print out the month on the input of the first character if there is only one month that starts with that character.

Example if F is input then February should be printed out, but if M is the first character then the program should request more characters before ot can print out a month.

5. Write algorithms and programs which will output the following patterns. You will need to make use of nested loops.

c _ HERIOT-WATT UNIVERSITY 2004

Page 45: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

45

Glossary

SimulationReplication of a process by computer that would not be possible to do manually. For example studying the projected traffic analysis of an airport or throwing a die many hundreds of times.

Answers to questions and activities

7 High Level Language Constructs 2

Revision (page 2)

Q1: c) Data items of the same type are grouped together Q2: c) Only the

first array element is set to some value Q3: d) Days(3) = "Wednesday"

Q4: c)1,8,3,9,5,6

Q5: b) Selection

Answers from page 14.Q6: d) Control loop variable is increasing in value by a constant amount determined by the

programmer

Q7: c) For loopCounter =(3*4) to (5*2) step 1

Q8: a) Calculating the total number of marks entered at a keyboard Q9: a) Triangle

Q10: c) 18

Answers from page 22.Q11: The value of n within the loop is never incremented. It will therefore always have a value of 0, which is less than 100, and hence this will produce an infinite loop whichwill never terminate. The program will therefore never end.

The code could be altered to include an increment e.g.

Let n = 0Do while n < 100 Let value = n*nLoop

c _ HERIOT-WATT UNIVERSITY 2004

Page 46: Prerequisite knowledge - Moodle · Web viewThe aim of this topic is to introduce you to iterative structures, or loops. Iteration simply means repetition, which in the context of

46

Q12: There is no loop to end the do…while. Add loop at the end of the code.

Q13: A typical solution to the problem is shown here.

Let sum = 0Let I = 0Do while I < 20

Let sum = sum + ILet I = I + 1

Loop

You should obtain a value of 210 for the sum of all the numbers between 0 and 20 inclusive.

Answers from page 28Q14: c) the loop need not be entered if the condition fails at the start.Q15: a) selectionQ16: b) 1 2 3 4 5Q17: b) 1Q18: d) Any on of the above

Indexing arrays (page 36)Q19: c) array= [0, 3, 0, 0]Q20: d) array= [7, 3, 0, 0]Q21: c) 2Q22: a) 3Q23: c) array = [8, 12, 5, 19, 3, 0, 7, 52]Q24: c) array = [8, 23, 5, 9, 3, 4, 7, 52]Q25: array = [0, 9, 3, 0]Q26: array = [0, 7, 0, 0, 6, 0, 0, 3, 2, 0]Q27: The program fragment which will help you do this is:-

For i = 0 to 9 Let myarray(i) = i

Answers from page 38Q28: d) all of the above optionsQ29: b) A for loopQ30: d) 0 4 6 2 5 7Q31: a) value_1(0) = “Hello”Q31: c) 11

c _ HERIOT-WATT UNIVERSITY 2004