software development programmingweb1.muirfield-h.schools.nsw.edu.au/technology/resources/ist/... ·...

30
15 CHAPTER 15 Syllabus outcomes 5.2.1 Describes and applies problem-solving processes when creating solutions. 5.2.2 Designs, produces and evaluates appropriate solutions to a range of challenging problems. 5.2.3 Critically analyses decision-making processes in a range of information and software solutions. Overview This chapter will develop your understanding of software development and programming. It examines the basic programming concepts, algorithms and control structures. You will learn about programming languages, testing and documentation. Software development and programming Software development and programming

Upload: buituyen

Post on 09-Mar-2018

228 views

Category:

Documents


1 download

TRANSCRIPT

15CH

AP

TE

R

15

Syllabus outcomes5.2.1 Describes and applies problem-solving processes when

creating solutions.

5.2.2 Designs, produces and evaluates appropriate solutions to arange of challenging problems.

5.2.3 Critically analyses decision-making processes in a range ofinformation and software solutions.

OverviewThis chapter will develop your understanding of softwaredevelopment and programming. It examines the basicprogramming concepts, algorithms and control structures. You willlearn about programming languages, testing and documentation.

Softwaredevelopmentandprogramming

Softwaredevelopmentandprogramming

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 331

332 HI Tech: In format ion and Software Techno logy

15. 1 ProgrammingProgramming is the process of writing programs and developingsoftware. A program is a collection of instructions that, whenexecuted, will complete a task on the computer. One or moreprograms are commonly referred to as software or code. Peoplewho write programs are called programmers or softwaredevelopers. Programmers write programs using programminglanguages. There are many programming languages available suchas Java, Visual BASIC and C++.

Java is a popular language developed by Sun Microsystems. Java,like all programming languages, has its own set of rules (syntax)which must be strictly followed (see Figure 15.1). However, thereare basic programming concepts in all programming languages.

Basic programming conceptsWhen writing a program it is necessary to consider the input,processing and output. Input is the data needed to solve theproblem, the processing is the calculations required and the outputis the way of giving the solution. Once these factors are determined,the actual task of writing programs is minimised. A program iswritten in a programming language using the following concepts.• Function (or keyword) is a reserved word for a particular

purpose such as class, public and private. Some functions arevery powerful, such as if and while.

Figure 15.1 Java program

Lit 8.1

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 332

33315 Software deve lopment and programming

• Constant (or literal) is an item of data with only one specific value.Constants are either numbers or strings (numbers and letters).

• Variable is an item of data that may take different values, one ata time. They are storage containers used to hold data of the sametype.

• Identifier is the name of anything in a program such as avariable. There are some restrictions on the use of identifiers,such as always starting with a letter.

• Separator is a symbol for grouping sections of the program suchas { and }. The correct use of separators is essential otherwisethe program will not work.

• Assignment statement gives a value to a variable such as: x = 9.The general form of an assignment statement is: variable =expression. The expression can contain other variables such as:y + 1. This will result in the assignment statement: x = y + 1.

GUI layoutThe graphical user interface (GUI, pronounced ‘gooey’) givesinstructions using a mouse, and clicking on icons and menus.A GUI provides an easy-to-use and consistent interface for a rangeof applications. Modern programming languages create objects foreach component in a GUI,such as:• text box and labels are

used to display text• option button (or radio

button) enables the userto select one option froma group

• check box, a text box anda small box that allowsthe user to click on oroff—more than oneoption can be selectedfrom a group

• list box presents the userwith two or more optionsthat are viewed using ascroll bar

• command buttons—OK toconfirm selection andCancel to quit. Figure 15.2 Visual basic

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 333

334 HI Tech: In format ion and Software Techno logy

Data typeData type is the kind of data that can be stored in a variable. Tocreate a variable it must be declared. Variable declaration involvesstating the data type of the variable and an identifier or uniquename for the variable. Most programming languages have thefollowing data types:• integer number is a whole number without fractional parts• floating-point number is a number with the fractional parts• boolean is used to store values that have one of two possible

states such as true or false• character is used to store one character such as a letter, number

or symbol• string is used to store more than one character.

Data operatorsData operators (or operators) are used to represent an action to beperformed such as a calculation. Operators are classified as:• Arithmetic operator—performs a calculation such as addition

(+), subtraction (–), division (/), multiplication (*), powers (^)and modulus (%). Calculations are carried out using thestandard order of operations.

• Relational operator—compares two values and returns aboolean (true or false) result. Relational operators include lessthan (<), greater than (>), less-than-or-equal-to (<=), greater-than-or-equal-to (>=), equal-to (= =) and not-equal-to (!=).

• Logical operator—compares two values and returns a boolean(true or false) result. Logical operators include AND (&&), OR(!!) and NOT (!).

Exercise 15.11 Explain the difference between:

a constant and variableb character and stringc an arithmetic operator and a relational operator.

2 What am I?a A collection of instructions that, when executed, will complete

a task on the computer.b The name given to anything in a program such as a variable.c A component in a GUI that enables the user to select one

option from a group.d Data type for whole numbers without fractional parts.

Interactive

Lit 8.2

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 334

33515 Software deve lopment and programming

3 Copy and complete the following by replacing the letter in brackets with a suitable term:People who write (a) are called programmers. A collection ofprograms is called (b). Programmers use (c) languages such as Java,(d) and C++.

4 a What is programming?b Describe the factors that minimise the actual task of writing

programs.c What is the purpose of an assignment statement?d What is a variable declaration?e List five common data types.f What is a data operator?

Development5 Examine the Java program in Figure 15.1.

a What is the purpose of this program?b How could you change this program to display your name?

6 Do research to find an example of a program written using aprogramming language.a Describe the input, processes and output.b Identify the data operators, functions, assignment statements,

variables and constants.

15. 2 AlgorithmsAn algorithm is a series of steps designed to solve a problem in afinite time. An algorithm can be used to solve many types ofproblems. Algorithms are not programs but are an important partin the development of a program. In this section we examinealgorithms from familiar but non-computing contexts.

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 335

336 HI Tech: In format ion and Software Techno logy

Algorithms can be used to describe simple daily actions orexplain a particular task. For example:

Algorithm to make a phone call:Pick up the phone.Dial number.Deliver the message.Hang up the phone.

Algorithm to catch a train:Travel to station.Buy a ticket.Go to the correct platform.If the correct train, catch the train, otherwise wait.Repeat the above step.

Algorithm to install a smoke alarm:Select a central location such as the hallway.Select a wall or ceiling on which to mount the alarm.Unlatch and remove the mounting plate from the alarm.Use the screws to secure mounting plate to ceiling.Install batteries into alarm body.Hook the alarm body onto the mounting plate.

In all of these examples the algorithm presents a solution in adefinite number of steps. Each step is short enough so that it can beeasily carried out. The steps must also be performed in a particularorder (sequence) to solve the problem; for example, you cannothang up the phone before delivering the message. Algorithms arerepresented in a number of different ways. These are referred to asmethods of algorithm description. There are many differentmethods of algorithm description such as pseudocode andflowcharts.

PseudocodePseudocode uses indented lines and keywords to describe analgorithm. Pseudocode is written using a word processor and issimilar to many programming languages. There are differentstandards of pseudocode for different purposes, however, there aresome generally accepted rules. The flow of control in pseudocode isalways from the top to the bottom. The keywords are highlighted incapital letters (or bold) to emphasise them and to indicate the typeof action being performed. The most common keywords are shownin Table 15.1. These keywords are grouped together in pairs. Forexample, for every BEGIN there is an END, for every IF there is anENDIF. Indentation is used to show the structure of the algorithm.

Before analgorithm can be written theproblem must befully understood.How a solution isarrived at dependsa lot on pastexperience. If asimilar problemhas been solved it is an obviousadvantage.

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 336

33715 Software deve lopment and programming

Table 15.1 Keywords used in pseudocode

Keywords Meaning

BEGIN Terminal: start and finishEND

IF (condition) Selection: different tasks are performed THEN process 1 according to the conditionELSE process 2 The ELSE statement is optional

ENDIF

WHILE (condition) Repetition: statements between the keywords process 1 are repeated while the condition is true

ENDWHILE (Pre-test repetition)

REPEAT Repetition: statements between the keywords process 1 are repeated while the condition is true

UNTIL (condition) (Post-test repetition)

Problem: Write pseudocode to calculate the area of arectangle given a length of 3 cm and a breadth of 5 cm.

Solution:BEGIN

Make length 3 cmMake breadth 5 cmSet area to length × breadthDisplay area

END

FlowchartsA flowchart is a pictorial or graphicalmethod of describing an algorithm.Flowcharts often make it easy to seethe structure of the solution. However,it is very easy to draw a flowchart that iscomplex and difficult to change into aprogramming language. The basicelements of a flowchart are a set ofsymbols that contain messagesand interconnecting lines. A set ofstandards for flowcharts has beenestablished for a number ofdifferent applications. The fourmost commonly used symbols areshown in Table 15.2.

Lit 8.3

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 337

338 HI Tech: In format ion and Software Techno logy

Table 15.2 Symbols used in flowcharts

Symbol Meaning

Terminal: start and finishThere should be only one line in or one line out

Process: used to describe a process or actionIt contains one line in and one line out

Subprogram: process described by its ownflowchart to perform a particular task

Decision: it consists of one line coming in at thetop and two lines leaving it

The Australian standards forflowcharting indicate that the maindirection of flow is from top to bottomor left to right. This flow of control isindicated by lines and arrows calledflowlines. Flowlines do not need an arrowif the flow of control is following thesemain directions. For example, in Figure15.3 the flow of control is from top tobottom so there are no arrows on theflowlines.

Problem: Design a flowchart tocalculate the area of a rectanglegiven a length of 3 cm and abreadth of 5 cm.

Solution: Figure 15.3 shows theflowchart for this problem.

Begin

Make length 3cm

Make breadth 5cm

Set area to length x breadth

Display area

End

Figure 15.3 Flowchart tocalculate area of a rectangle

Set count to thirty

Set count to thirty

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 338

33915 Software deve lopment and programming

Exercise 15.21 Copy and complete the following sentences:

a Algorithms are not _______ but are an important part in thedevelopment of a program.

b _______ uses indented lines and keywords to describe analgorithm.

c The flow of control in pseudocode is always from the _______ tothe bottom.

d A flow chart is a _______ method of describing an algorithm.2 What am I?

a A method of algorithm description that is written using a wordprocessor.

b A keyword in pseudocode to start the algorithm.c The lines and arrows in a flowchart.d A symbol used in a flowchart to start and finish.

3 The following algorithms have errors in their sequence. Find theseerrors and write the correct solution to the problem.a Algorithm to read a book:

Read bookOpen book to first pageClose bookGet book

b Algorithm to run a bath:

If bath is full, turn off the tapsIf water is too hot, increase the amount of cold waterPut plug into bathIf water is too cold, increase the amount of hot waterTurn on the hot water tapTurn on the cold water tap

4 a What is an algorithm?b Why must the steps in an algorithm be performed in a

particular order?c Why are the keywords in pseudocode highlighted?d What is the purpose of indentation in pseudocode?e What are the disadvantages of a flowchart?f Name the basic symbols used in flowcharts.

Development5 An algorithm to watch your favourite television show is shown

below:

Turn television onSelect television showWatch television showTurn television off

a Convert this algorithm into pseudocode.b Convert this algorithm into a flowchart.

ICT 15.1

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 339

340 HI Tech: In format ion and Software Techno logy

6 An algorithm to listen to a CD is shown below:

Turn on equipmentInsert CDSelect trackPlay

a Convert this algorithm into pseudocode.b Convert this algorithm into a flowchart.

7 Design an algorithm in both pseudocode and a flowchart for thefollowing:a making a cheese sandwichb making a bowl of cereal for breakfast.

15. 3 Control structuresProgrammers solve a problem by designing an algorithm and thencoding the algorithm into a programming language. Algorithmsand programming languages consist of control structures. Controlstructures are the building blocks of the program. There are threebasic control structures: sequence, selection and repetition.

SequenceSequence is the order the steps are executed. In pseudocode, thesteps are placed between BEGIN and END (see the problem below).The sequence of four steps is indented to show structure and toimprove the readability of the algorithm. The flow of control is topto bottom, starting at the first step and finishing at the last step.Flowcharts always start and finish with a terminal symbol (oval).The steps are placed between these symbols and joined by flowlines(see Figure 15.4). The direction of flow is down the page betweenthe terminal symbols.Problem: Design an algorithm to wash your hands.Pseudocode solutionBEGIN

Wet handsClean hands with soapRinse off soapDry hands

ENDFlowchart solution is shown in Figure 15.4.

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 340

34115 Software deve lopment and programming

SelectionSelection is used to make a logical decision. It requires a choice tobe made between two or more options. The choice is madedepending on the answer to a condition. There are two types ofselection: binary and case.

Binary selection involves two choices. In pseudocode, thekeywords IF … THEN … ELSE are used for binary selection (see the problem below). The condition is put after the IF keyword.There are only two possible answers to the condition, true or false.If the condition is true then the process after the THEN keyword isexecuted. If the condition is false then the process after the ELSEkeyword is executed. The ELSE statement is not always requiredand can be omitted. In a flowchart the selection is made using adecision symbol (diamond). The condition is placed inside thissymbol and the answer must be true or false (see Figure 15.5). It isvery important that the two flowlines from the decision symbol arelabelled with true or false to determine which path to follow. Thetwo flowlines join together to complete the binary selection.

Begin

Wet hands

Clean hands with soap

Rinse off soap

Dry hands

End

Figure 15.4 Flowchart towash your hands

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 341

342 HI Tech: In format ion and Software Techno logy

Problem: Design an algorithm for turning on the lights.Pseudocode solutionBEGIN

IF nightTHEN turn lights onELSE turn lights off

ENDIFENDFlowchart solution

Case selection (or multiway selection) involves more than twochoices. In pseudocode, the keywords CASEWHERE … ENDCASEare used for case selection (see the problem below). The conditionis put after the CASEWHERE keyword. Careful thought is requiredto cater for all possible answers to the condition. The possibilitiesare indented under the CASEWHERE keyword with a process to beexecuted only if the answer is true. In the problem below there arethree options: green, amber and red with a colon specifying theprocess to be carried out if the option is true. In a flowchart thecase selection is made using a decision symbol (see Figure 15.6).The condition is placed inside the decision symbol with theanswers above each process. The flowlines join together to completethe case selection.

Problem: Design an algorithm for a set of traffic lights.

Begin

TrueFalse

End

Turn lights onTurn lights off

Is it night?

Figure 15.5 Flowchart for turning on the lights

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 342

34315 Software deve lopment and programming

Pseudocode solutionBEGIN

CASEWHERE colour of signalGreen : Pass through lightsAmber : Slow down vehicleRed : Stop vehicle

ENDCASEENDFlowchart solution

RepetitionA repetition or loop allows a number of steps to be repeated untilsome condition is satisfied. The steps to be repeated are referred toas the body of the loop. It is very important that each loop containsa condition to stop the loop going on forever. There are two typesof repetition: pre-test or post-test.

In a pre-test repetition or guarded loop the condition is checkedat the beginning of the loop before the steps to be repeated areexecuted. In pseudocode the keywords used for a pre-test repetitionare WHILE … ENDWHILE (see problem below). The condition isput after the WHILE keyword and the body of the loop betweenthe WHILE and ENDWHILE keywords. In a flowchart the pre-testrepetition is made using a decision symbol and flowlines (seeFigure 15.7). The condition is placed inside the decision symboland checked before the body of the loop.

RedAmberGreen

Begin

End

Pass through lights Stop vehicleSlow down vehicle

Colour of thesignal is?

Figure 15.6 Flowchart for a set of traffic lights

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 343

344 HI Tech: In format ion and Software Techno logy

Problem: Design an algorithm for using seat belts in a car.Pseudocode solutionBEGIN

WHILE car is movingkeep seat belts on

ENDWHILEENDFlowchart solution

In a post-test repetition or unguarded loop the condition ischecked at the end of the loop after the steps to be repeated areexecuted. In pseudocode the keywords used for a post-test repetitionare REPEAT … UNTIL (see problem below). The body of the loopis underneath the REPEAT keyword and the condition is after theUNTIL keyword. In a flowchart the post-test repetition is made witha decision symbol and flowlines (see Figure 15.8). The body of theloop is executed before the condition is met in the decision symbol.

Problem: Design an algorithm to cut the grass.Pseudocode solutionBEGIN

REPEATUse lawn mower

UNTIL grass is cutEND

False

True

Is car moving?

Keep seat belts on

Begin

End

Figure 15.7 Flowchart for using seat belts in a car

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 344

34515 Software deve lopment and programming

Flowchart solution

Exercise 15.31 What control structures are represented by the following

algorithm segments?a BEGIN

process 1process 2process 3

ENDb WHILE (condition)

processENDWHILE

c IF (condition)

THEN process 1ELSE process 2

ENDIFd REPEAT

ProcessUNTIL (condition)

e f

Figure 15.9 Figure 15.10

False

True

False

True

Use lawn mower

Is grass cut?

Begin

End

Figure 15.8 Flowchart to cut the grass

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 345

346 HI Tech: In format ion and Software Techno logy

g h

Figure 15.11 Figure 15.12

2 True or false?a Case selection involves two choices.b In a flowchart a selection is made using a decision symbol.c The steps repeated in a repetition are called the body of the loop.d The REPEAT … UNTIL keywords are used for a pre-test repetition.

3 Copy and complete the following by replacing the letter in bracketswith a suitable term:The building blocks of a program are called the (a). Sequence is the(b) the steps are executed. Selection is making a logical (c).Repetition allows a number of (d) to be repeated.

4 a What is the sequence in an algorithm?b Describe the flow of control in pseudocode.c What is binary selection in an algorithm?d Why is it important to label the two flowlines from a decision

symbol with true or false?e What keywords are used for a pre-test repetition in

pseudocode?f How is a post-test repetition made in a flowchart?

Development5 Explain what the following algorithms do.

a Pseudocode:

BEGINprint ‘What is the capital of Australia?’get answer from userIF answer is Canberra

THEN print ‘Well done, correct’ELSE print ‘Sorry the answer is Canberra’

ENDIFEND

b Pseudocode:

BEGINset Count to oneWHILE Count is less than eleven

print Countincrement Count by one

ENDWHILEEND

TrueFalse False

True

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 346

34715 Software deve lopment and programming

c Pseudocode:

BEGINset Count to tenREPEAT

print Countincrement Count by one

UNTIL Count is twentyEND

d e

Figure 15.13 Figure 15.14

f

Figure 15.15

End

Begin

Is colourblue?

TrueFalse

Print ‘You are wrong,blue is the answer’

Print ‘Congratulationsyou are right’

Print ‘What is myfavourite colour?‘

Input colour

Begin

False

True

End

Is Count lessthan eight?

Print Count

Decrease Count by two

Set Count to thirty

False

True

Begin

End

Set Count to twenty

Is Count> 0?

Print Count

Decrease Count by one

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 347

348 HI Tech: In format ion and Software Techno logy

6 Convert these algorithms into pseudocode and flowcharts:a Go to the bus stop

Wait for the busGet on busPay fare

b Alarm goes off

Get out of bedIf I have homework to complete, then finish homeworkGet dressedEat breakfast

c Go to the lounge room

Turn on the TVIf it is Sunday, then watch a movie else watch news

d Wake up

Get out of bedHave a showerIf weekday, then put on uniform else put on normal clothesEat breakfast

e Go to the station

Buy a ticketBuy a magazineSit on a seat and read a magazine until the train comesPut magazine in bagGet on the train

7 Construct an algorithm in pseudocode for the following tasks:a making a phone callb cleaning your teeth.

15. 4 ProgramminglanguagesProgramming languages are used to create the instructions in aprogram that can be understood by the computer. Eachprogramming language has its own set of rules that must be strictlyfollowed. The rules of the programming language are called itssyntax. Programming languages are divided into two groups:• Low-level languages are the lowest level of computer languages

and depend on the hardware of the computer. Programs writtenusing low-level languages are often called machine code orassembly code. They process calculations much faster thanhigh-level languages.

• High-level languages use English-like codes where each statementcorresponds to several lines of machine code. Programming

Tutorial

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 348

34915 Software deve lopment and programming

languages such as Java, Visual BASIC and C++ are high-levellanguages. A compiler or interpreter translates a high-level programinto machine code so the computer can implement the solution.

Object-oriented programmingMost programmers use a high-level language and a strategy calledobject-oriented programming or OOP (rhymes with hoop). OOPrequires the programmer to package the data and the methods (orprocedures) into a single unit called an object. A program consistsof a collection of interacting objects. Writing a program involvesdescribing different types of objects—what they can do, how theyare created and how they interact with other objects. Creating anobject requires defining that object. This is called creating a class.A class describes how objects behave and the kind of informationin the object. It is a template to create objects. After defining classesand creating objects programmers write instructions to complete atask. A task could be adding numbers or completing a simple game(see Figure 15.16).

Object-oriented programming requires keywords, literals,variables, identifiers, separators, data types and operators. Theseconcepts were examined at the start of this chapter. Java is apopular language developed by Sun Microsystems to create smallapplications. It is an object-oriented language that excels atproducing web-based applets that work on different types ofcomputers. Applets are graphical Java programs that execute withina web page. They are responsible for the dynamic nature of the Web.The Java software development kit has all the tools and resourcesneeded to write Java applets and applications. The Java program iswritten in a text editor and a Java compiler used to convert theprogram into source code for an HTML document. The controlstructures used in Java are similar to pseudocode:

Figure 15.16 Instructions in Visual Basic

Lit 8.4

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 349

350 HI Tech: In format ion and Software Techno logy

• sequence—execute one after another from the start to the end• binary selection—uses the if–else keywords:

if (condition)Statement 1

elseStatement 2

• case selection—uses the switch–case keywords:switch (Expression)

case Constant 1:StatementList1

case Constant 2:StatementList2

default:DefaultStatementList

• pre-test repetition—uses the while keyword:while (LoopCondition)

Statement

• post-test repetition—uses the do–while keywords:do

Statementwhile (LoopCondition)

Problem: Write a Java program that will ask the user fortheir first name and print this name ten time on the screen.Pseudocode solutionBEGIN

set Count equal oneinput user’s nameWHILE Count is less than or equal to 10

print user’s nameincrement Count by one

ENDWHILEENDJava solution is shown in Figure 15.17

SubprogramsStructured programming aims to create well ordered and logicalprograms. It involves breaking the problem down into smallerparts. Each part is solved separately and then combined to producethe final solution. A structured program consists of a collection ofsmaller programs. Each of these smaller programs is called asubprogram. A subprogram is a self-contained section of code thatperforms a particular task. In Java, subprograms are called ‘methods’.For example, the code below is a method in Java. It adds twointegers (parameters) and returns the result to the calling program(larger program).

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 350

35115 Software deve lopment and programming

Public int add2Int (int x, int y){

Int result;result = x + yReturn result;

}

Subprograms have a single entry point and suspend the callingprogram until they have finished.Subprograms have the addedadvantage of being reuseable.Programmers may use the samesubprogram many times in differentproblems. This reduces the timerequired to program. Programmerskeep a ‘library’ of subprograms theyhave written.

Data structuresA file is a block of related datastored on a storage device.Programs are stored as files. A data structure used in manyprogramming languages is called a record.

A record is a collection of facts that are related in some way.Records are a fixed length and are divided into one or more fields.A field is a specific piece of data in a record. Shown below is arecord that consists of 17 characters: eight for field 1, seven for field2 and two for field 3. Each record, irrespective of the data, wouldhave a fixed length of seventeen characters. A record is usually acombination of other data types. The record below has a string datatype and an integer data type. The ability to have different datatypes distinguishes records and arrays.

s m i t h l u k e 1 6

An array stores a list of elements of the same data type. An arrayis used to efficiently store large quantities of data. Each elementwithin an array is numbered and accessed based on their number.To use an array the data type and the number of items must bedeclared. For example, array declarations in Java are shown below.

Int[] score = new int[10];char[] vowel char[5];

Figure 15.17 Java program

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 351

352 HI Tech: In format ion and Software Techno logy

The first statement creates an integer array ‘score’ with up to tenelements. The second statement creates a character array ‘vowel’with up to five elements. After the array is declared each individualelement can be used to store data. In the example below vowel[1] isstoring the letter ‘E’.

vowel[0] = ‘A’;vowel[1] = ‘E’;vowel[4] = ‘U’;

Exercise 15.41 True or false?

a Each programming language has the same rules that must bestrictly followed.

b Most programmers use a high-level language.c A class describes how objects behave and the kind of

information in the object.d Object-oriented programming involves breaking the problem

down into smaller parts.2 Explain the difference between:

a a low-level language and a high-level languageb a record and an array.

3 Copy and complete the following sentences:a A program in _______ consists of a collection of interacting

objects.b A _______ is a self-contained section of code that performs a

particular task.c Each element within an array is _______ and accessed based on

their number.4 a What is the purpose of a programming language?

b Describe the process of writing a program using an OOPlanguage.

c What are applets?d What is the aim of structured programming?e Describe an advantage of subprograms.f What is the purpose of an array?

Development5 Do research into a high-level programming language. If possible

complete a tutorial on a programming language. Identify the basicprogramming concepts and control structures used in the programminglanguage. Write a report that summarises your investigation.

6 Write a program that will ask the user for their first name and printthis name ten times on the screen (see Figure 15.17). Execute thisprogram. Modify the program so that the person’s name is printedtwenty times.

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 352

The term ‘bug’ is a result of aproblem with theMark 1 computerin 1945. Thiscomputer startedworking after amoth was removedfrom the inside ofthe machine.Consequently, anyunknown problemwith a computer issaid to be a ‘bug’.

35315 Software deve lopment and programming

7 Write a program that will create an array and store each letter ofthe alphabet. Enter data into the array and use the array to displaya message.

15. 5 Testing anddocumentationMost programmers strive for the perfect program, however, few areable to achieve it. It is rare for a complex program to be writtenwithout errors. Errors in a program are called bugs. A bug is anerror that makes the program run incorrectly. The process offinding a bug is called debugging. Debugging is often a time-consuming and challenging task.

TestingTest data is used to detect and correct any potential errors in aprogram. Except for simple programs, test data will only cover asmall percentage of all the possible sets of data. The programmerselects test data that will cater for the ‘worst-case’ situation. This isdata the programmer predicts will cause a problem. It is often dataoutside the boundaries of acceptable data such as entering a decimalnumber instead of an integer. Test data is also designed to check forexpected outcomes. For example, if a user enters 4 the programshould display the result for this value. The selection of test datadepends on the programmer’s understanding of the program.Programmers use test data throughout the development of a program.

Error detection and correctionError detection involves identifying and describing the error. Errorcorrection fixes the source of the error to create a workable program.There are three basic types of errors:• Logic errors result from an incorrect series of steps to solve the

problem. The program with a logic error produces incorrect orunexpected results. Logic errors can occur if the algorithm doesnot solve the problem correctly. The algorithm should be testedbefore coding to eliminate logic errors. It is often a difficult taskto find and correct logic errors.

• Syntax errors are made when the programmer has failed tofollow the rules (syntax) of the programming language. A syntaxerror may be a spelling error or a symbol that cannot be

Lit 8.5

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 353

A trapdoor is asection of codeused byprogrammers as adiagnostic tool toenable them toaccess certain partsof a program.Trapdoors areremoved before aprogram is sold.

354 HI Tech: In format ion and Software Techno logy

translated. When the program is compiled or interpreted, anerror message will appear if the program contains any syntaxerrors. Correcting any syntax errors is usually a simple task.

• Run-time errors occur when it is impossible for the computer tocarry out the instruction. For example, if a calculationattempted to divide a number by zero it would be a run-timeerror. The instruction has the correct syntax but it is notpossible to carry out the instruction. Incorrect data can oftenproduce a run-time error.

There is a range of strategies to detect and correct errors:• Desk checking involves the programmer checking each line of

code. Desk checking takes place after the algorithm has beenwritten and again after it has been coded in the programminglanguage. The programmer executes the program the same asthe computer. Desk checking provides a way to see exactly whatcode is being executed and the flow of execution through theprogram. A desk check usually involves watching the variables.A list is constructed containing the names of variables and theirvalues. The list of variables is updated after each step of the deskcheck. If the desk check is performed by somebody other thanthe programmer it is called a peer check.

• Breakpoint is a roadblock in the execution of the program.When the program reaches a breakpoint it stops. Breakpointsare useful in isolating sections of the code and analysing them.

• Software debugging tools are available for most programminglanguages. A debugger is a program that will perform the deskcheck electronically. They are often used with a breakpoint towatch the variables in a section of code. Debuggers are only toolsto find problems and do not provide the solution to the problem.

DocumentationDocumentation is a written description to explain the developmentand operation of a program. It is not part of the actual code.Documentation is an important aspect of writing programs as ithelps the reader to understand what is going on. It should be writtenduring the development of the program, however, it is often neglectedand left until last. This results in inadequate documentation makingthe program difficult to understand and modify. The documentationrequired in a program falls into three main categories:• Intrinsic documentation involves writing an easy-to-read

program. It involves using correct programming techniques andmeaningful variable names such as ‘height’ instead of ‘x’.

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 354

35515 Software deve lopment and programming

• Internal documentation consists of any comments or remarkswithin the program code to describe its purpose. The codebelow shows internal documentation in Java using the forwardslash and asterisk:/* This form of documentation allows the text to wrap

around onto succeeding lines*/// This form of documentation is restricted to one line

• External documentation consists of any written supportmaterial. This may include a problem statement, input data,output data, processes, algorithm, test data and a listing of theprogram, user manuals and installation guides.

Project: Rite SoftwareArla is a programmer who has been contracted to update the userinterface for Rite Software. Rite Software is a suite of programs to helpchildren read and write. The user interface was written seven years agoand looks dated. She solved the problem using the four stages inproject development.

• Define and analyse the problem: Arla spoke with the manager todetermine the exact requirements of the problem. She collectedinformation to be displayed on the screen. A project plan waswritten and submitted for approval to the manager.

• Design possible solutions: Arla designed four possible screens. Eachpossible solution had the same objects; however, they wereformatted and displayed in different ways. A feasibility report waswritten and presented to the manager. The recommendation fromthe feasibility report was accepted by the manager. Arla designedan algorithm using pseudocode to solve the problem.

• Produce the solution: Arla used Visual BASIC programminglanguage to code the algorithm. She created forms and addedobjects to those forms. The properties of each object werespecified. Arla entered the code and saved the project.

• Evaluate the solution: Arla tested the program to ensure eachscreen and form was working correctly. There was a problemdisplaying one of the images and this was fixed. The new softwarewas presented to the manager.

Tasks1 Design an appropriate introductory screen for Rite Software using a

modern user interface.

2 What are the characteristics of a modern user interface?

ICT 15.2

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 355

356 HI Tech: In format ion and Software Techno logy

Exercise 15.51 What am I?

a An error made when a programmer has failed to follow therules of programming.

b An error that occurs when it is impossible for the computer tocarry out the instruction.

c An error detection that involves putting a roadblock in theexecution of the program.

d Documentation that involves writing an easy-to-read program.2 Copy and complete the following sentences:

a When a program is _______ an error message will appear if theprogram contains a syntax error.

b A desk check usually involves watching the _______.c A _______ is a program that will perform the desk check

electronically.d Inadequate _______ makes a program difficult to understand

and modify.3 Unjumble these words:

a ugdinebggb ecdk hkiecncg

4 a What is a bug?b What is the purpose of test data?c List the three basic types of errors.d What is desk checking?e Why is documentation an important aspect of writing

programs?f Explain the difference between internal and external

documentation.

Development5 Examine the following algorithm. What will be the output if the

user enters 4? Perform a desk check by watching the variables(Number, Count and Temp).

BEGINGet Number from the userSet Count to zeroWHILE Count is less than Number

Set Temp to Count plus onePrint Tempincrement count by one

ENDWHILEPrint Count

END6 Examine the following algorithm. What will be the output?

Perform a desk check by watching the variables (X and Y).

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 356

35715 Software deve lopment and programming

BEGINSet X to zeroSet Y to oneREPEAT

Set X to X plus YPrint Xincrement Y by one

UNTIL Y is fourPrint Count

END7 Edit the programs created in Exercise 15.4, Questions 6 and 7 by

inserting appropriate documentation.

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 357

358 HI Tech: In format ion and Software Techno logy

1 Which of the following is a reservedword for a particular purpose?a Variableb Separatorc Constantd Function

2 Which of the following describes adata type to store a value that hasone of two possible states such astrue or false?a Booleanb Stringc Floating-pointd Yes/no

3 Which of the following statements isincorrect?a Algorithms present a solution in a

definite number of stepsb Keywords in pseudocode are

highlighted to indicate the type ofaction being performed

c Flowcharts are easier thanpseudocode to convert into aprogramming language

d Flow of control is indicated bylines and arrows called flowlines

4 Which method of algorithmdescription uses keywords groupedin pairs?a Pseudocodeb Flowchartc Javad Visual BASIC

5 What control structure is representedby the following algorithm segment?

CASEWHERE (condition)process 1process 2

ENDCASE

a Case repetitionb Case sequencec Case selectiond Case algorithm

6 Which of the following is a loopchecked at the end after the steps tobe repeated are executed?a Pre-test repetitionb Post-test repetitionc Pre-test selectiond Post-test selection

7 Which of the following is a self-contained section of code thatperforms a particular task?a Arrayb Subprogramc Programming languaged File

8 Which of the following requires aprogrammer to package data and themethods into a single unit called anobject?a OOPb GUIc Low-level languagesd High-level languages

9 Which of the following is the resultfrom an incorrect series of steps tosolve the problem?a Syntax errorb Run-time errorc Logic errord Desk check

10 Which of the following describescomments or remarks within theprogram code to explain its purpose?a Comment documentationb External documentationc Intrinsic documentationd Internal documentation

Part A: Multiple choice questionsSelect the alternative (a), (b), (c) or (d) that best answers each question.

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 358

35915 Software deve lopment and programming

Part B: Match the termFor each of the following statements (1 to 10), select from the list of terms (a to j)the one that most closely fits the statement.

Statements

1 A collection of instructions that,when executed, will complete a taskon the computer.

2 The kind of data that can be storedin a variable.

3 A series of steps designed to solve aproblem in a finite time.

4 A method of algorithm descriptionthat uses indented lines andkeywords.

5 A method of algorithm descriptionthat uses a pictorial or graphicalmethod.

6 Control structure that specifies theorder the steps are executed.

7 Control structure used to make alogical decision.

8 Data structure that stores a list ofelements of the same data type.

9 It is used to detect and correct anypotential problems in a program.

10 A written description to explain thedevelopment and operation of aprogram.

Termsa Algorithmb Arrayc Data typed Documentatione Flowchart

f Programg Pseudocodeh Selectioni Sequencej Test data

Part C: Extended response questionsWrite at least one paragraph for each of the following:

1 Variable declaration involves statingthe data type of the variable. Brieflydescribe five different data typesthat are commonly used in programs.

2 Explain the purpose of dataoperators. Identify and describe threedifferent types of operators.

3 Pseudocode and flowcharts are twopopular methods for algorithmdescription. Outline the mainfeatures of these methods.

4 Explain the difference between:a binary selection and case selectionb a pre-test repetition and a post-

test repetition.5 What is a high-level language?

Outline the processes involved instructured programming.

6 Testing should be done throughoutthe development of a program todetect errors. Describe three basictypes of errors. Which type of errorusually takes the longest to correct? Give reasons for your answer.

e Tester

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 359

360 HI Tech: In format ion and Software Techno logy

Project: Arithmetic programMax is a primary teacher who needs software to test his student’s arithmetic skills.The program should present students with ten problems to add and subtractnumbers. The numbers selected should be done randomly and not require thestudent to calculate negative numbers. The program should total the number ofcorrect answers and store their results for Max. This is a group project to bedeveloped using the four stages in project development. Demonstrating theoperation of the arithmetic program and documenting the solution are importantcriteria for this project.

Project 8.1

Project 8.2

Project 8.3

Cross project 3

313 ISTech Chapt 15.3pp 23/9/04 12:45 PM Page 360