You are on page 1of 49

Problem-solving and Program Design

End-of-topic questions 1 1. List the main stages you should go through when trying to solve a general problem. A. Stage 1: Define the problem Stage 2: Analyse the problem Stage 3: Propose and evaluate possible solutions Stage 4: Select and ustify the optimal solutions Stage !: "mplementation and revie# 2. Variables and constants are both identifiers. Explain the difference between them. $ariables are identifiers that are capable of changing their values% constants are identifiers that have fi&ed values. 3. What is the difference between an integer and a floating point number "ntegers are #hole numbers' positive or negative #ithout decimal places% floating point or real numbers are positive or negative numbers #ith decimal values. End-of-topic questions 2 1. What is an algorithm An algorithm is a finite number of accurate' unambiguous steps that solve a problem or tas(. 2. List four characteristics of a good algorithm. )he number of steps must be finite% the steps must be precise% the steps must be unambiguous% the steps must terminate. 3. What are the three main steps involved in creating an algorithm A. "nput step% processing step% output step !. What is meant by assignment A. Assignment is #here values are allocated to variables. End-of-topic questions 3 1. "ame three types of control structures that are commonly used in programming languages. A. Se*uencing' selection and repetition. 2. #tate the difference between bounded iteration and unbounded iteration. A. +ounded iteration is the repetition of a set of instructions a fi&ed number of times% unbounded iteration is repeating a set of steps a number of times until a particular condition becomes false. 3. $ive one example of a statement used in the following control structures% a. #election if,then,else b. &ounded iteration for,endfor c. 'nbounded iteration #hile,end#hile End-of-topic questions 4 1. (or each of the following problem statements% a. identify the input) output and processing steps. b. write the algorithm.

a. "nput

Write an algorithm to read three numbers and find their product. Processing Accept numbers 1alculate product Store results in product Display product .utput Product Step 1: start

)hree numbers /num1' num2'num30

Step 2: read num1' num2' num3 Step 3: product num1-num2-num3 Step 4: #rite product Step !: stop

A. "nput

Write an algorithm that displays the area of a rectangle by accepting length and width from the user. a. Step 1: start Processing .utput Accept length' #idth 1alculate area Store results in area Display area Area

length' #idth

Step 2: read length' #idth Step 3: area length - #idth Step 4: #rite area Step !: stop 3. Write an algorithm that will read the radius of a circle and calculate and display its perimeter. A. a. Step 1: start "nput Processing .utput circumference

Accept radius radius 1alculate circumference Store results in circumference Display circumference Step 2: read radius Step 3: circumference 2 - 3.14- radius Step 4: #rite circumference Step !: stop

End-of-topic questions 5 1. Write a narrative algorithm that will accept the radius of a circle and calculate and display its area. A.

"nput radius

Processing Accept radius 1alculate area Store results in area Display area

.utput area

Step 1: Start

Step 2: 2et radius Step 3: 1alculate area by using the formula 3.14 - radius - radius and store it in area Step 4: Display the area Step !: Stop 2. Write a pseudocode algorithm that will accept three numbers and calculate and display the largest of the three. A. "nput )hree numbers Processing Accept three numbers 1alculate the total Store results Display the result .utput Sum

3ead a' b' c Sum a4b4c 5rite sum 3. Write a pseudocode algorithm that will accept the mar*s in a test for a group of 2+ students then calculate and display the average mar*. A. "nput )hree numbers Processing Accept t#enty,five numbers 1alculate the total Store results in sum 1alculate the average Display the average .utput Average

)otal 6 7 8or " 6 1 to 2! 3ead mar( )otal 6 total 4mar( 9ndfor Average 6 total:2! 5rite average !. ,dd steps to the previous algorithm so it also displays the highest mar*. A. ;argest 6 7 8or " 6 1 to 2! 3ead mar( "f mar(<largest then largest 6 mar( endif

)otal 6 total 4mar( 9ndfor Average 6 total:2! 5rite average Chec !our progress 1 1. -raw flowcharts for the following programs% a. .rogram to accept the price of an item and calculate its V,/ at 1+0.

start

read price

vat price -.1!

#rite vat

stop

b.

.rogram to accept money in '# dollars and convert it to its e1uivalent local currency.
start

read us

ec us -2.=1

#rite ec

stop

c.

.rogram to accept the length and width of a rectangle and calculate its area.
start

read length' #idth

area 6 length - #idth

#rite area

stop

End-of-topic questions " 1. -raw flowcharts for the following% a. , program that accepts 22 numbers and finds their product.
start

product 6 1 numcount 67

read num

product 6 product - num numcount 6numcount 41

is numcount>627

no yes

#rite product

stop

b.

, program that accepts !+ numbers and finds the number of 3eroes and non43eroes in them.
stop

numcount 67 poscount 6 7 negcount 67

read num

yes

no if num<7

poscount 6poscount 41

negcount6 negcount41

yes is numcount>64!

no

#rite product

stop

c. , program that accepts a set of integers and finds the number of positive and negative numbers. /he program stops when the user enters 2 for the integer value.
stop

numcount 67 poscount 6 7 negcount 67

read num

yes

if num<7

no

negcount6 negcount41 poscount 6poscount 41

no yes is numcount>64! #rite product

stop

d. , program that accepts a set of numbers and finds the smallest among them. /he program stops when the user enters number 555.

start

smlst ,1

read num

is num8 9555

no 6 sum 4 num

yes no =

sum + num

= sum + :s num num9smlst

yes sum 4 num smlst num

read num

#rite sum

stop

Chec !our progress 2 1. 6reate a trace table to determine the output of the following algorithm% #tep 1% set x + #tep 2% set y 12 #tep 3% set 3 3 #tep !% set x x7y

#tep +% set y x 73 #tep ;% set 3 x7y73 #tep <% display x) y)3 A. & ! 17 3 1! 1@ 3A )he output #ill be 1!' 1@' 3A Chec !our progress 3 6reate a trace table to determine the output of the following algorithm% #tep 1% set a 12 #tep 2% set b 12 #tep 3% set c 23 #tep !% set a a7b7c #tep +% set b a4b #tep ;% set c b4c #tep <% if a9b then set m a set n b set p c else set m c set n a set p b endif #tep =% display m)n)p A. a 17 12 23 4! 33 17 4! )he output #ill be 4!' 33' 17 Chec !our progress 4 1. 6reate a trace table to determine the output of the following algorithm% #tep 1% set a < 33 17 b c m n p y ?

#tep 2% set x 1 #tep 3% While a892 set x x 7 a set a a 1 #tep !% endwhile #tep +% write x A. a = 1 @ A 14 ! 1B 4 23 3 2A 2 2@ 1 2B 7 )he output #ill be 2B. End-of-topic questions # 1. 6reate a trace table to determine the output of the following algorithms% #tep 1% x + #tep 2% for i 1 to 12 set x > x 7 + endfor #tep 3% write x A. & ! 1 17 2 1! 3 27 4 i &

2! ! 37 A 3! = 47 @ 4! B !7 17 !! )he output #ill be !!. Chec !our progress 5 1. What is meant by stepwise refinement or top4down design )op,do#n design or step#ise refinement is converting a bigger problem into main tas(s and subtas(s. )he ma or tas(s are completed first and the sub,tas(s are completed after. 2. List three advantages of using top4down design to solve a problem. 3eusability C sections of algorithm can be used again in other algorithms that re*uire a similar solution' #hich saves time in future development of algorithms% 9asy to follo# C as each tas( or subtas( performs only one function% 9asy to maintain C as each tas( is by itself' if there is a need for change in one tas( you need to concentrate on that tas( only. End-of-topic questions $ 1. Explain why a top4down design approach is sometimes used to solve problems. A. 5hen #e consider a problem it is often easier to vie# the problem as a #hole' and then brea( it do#n into smaller problems. 5e can then concentrate on one of the smaller problems and leave the others until later. 2. , hotel wants to have a room boo*ing system. When a guest arrives the receptionist would be able to see which rooms are free and allocate one to the guest. When the guest leaves) the room would be mar*ed as free again. Each day the cleaners would be given a list of the rooms that are in use. ,t any time the receptionist would be able to use the room number to find the name and home address of a guest) or could search the room system for a named guest. -raw a top4down design diagram to show how the room boo*ing system could be developed. A. Room booking

Room allocation

Cleaning tasks

Searches

Search for name and address of guest

Search for room occupied by guest

End-of-section questions - %ultiple-choice questions 1. /he following are problem4solving stages :. analyse the problem ::. suggest possible solutions :::. implement and review :V. define the problem V. select the best solution /he correct order of stages is% , :) :V) ::) :::) V & :V) :) ::) V) ::: 6 :V) ::) :) V) ::: - :) ::) :V) :::) V A. + 2. Which one of the following is a variable ,x & ?x@ 6 + - ?+@ A. A 3. /o store fractional values) use the data type% , integer & floating point 6 character A. +

- string

!. Which of the following is not a characteristic of a good algorithm , precise & finite number of steps 6 ambiguous - logical flow of control A. 1 +. -iagrammatic representation of an algorithm is% , flowchart & data flow diagram 6 algorithm design - pseudocode A. A ;. Which of the following isAare control structures , selection & se1uencing 6 repetition - all of the above A. D <. ,n example of a bounded iteration statement used in algorithm is% , whileBendwhile & whileBwend 6 forBendfor - repeatBuntil A. 1 =. Which one of the following is a selection construct used in algorithms , while Bendwhile & if B then 4 else 6 for Bendfor - repeat4until

A.

5. Which one of the following involves a logical operation , x9y & x9>y 6 x9y and x>y - x8 9y A. 1 12. 6onsider the following algorithm segment% x > x7y y>xy write y) x #uppose x > 12 and y > 1+) after the completion of the above statements) the values of x and y will be% , 2+ and 12 & 12 and 2+ 6 12 and 4+ - 4+ and 12 A. + &tructured questions 1 a. List the main stages of problem4solving process for computer4based problem4solving. b. (or each of the stages identified in 1a above) briefly describe the activities that are involved in it. A. a. Stage 1: Definition of the problem Stage 2: Analyse the problem Stage 3: Propose and evaluate possible solutions Stage 4: Develop and represent an algorithm Stage !: )est and validate the algorithm Stage A: "mplement the algorithm b. Stage 1: Definition of the problem "n this stage' the problem is loo(ed at carefully and if it is not phrased properly' it is modified to ensure that it is clearly stated. Stage 2: Analyse the problem "n this stage' identify the inputs to be used' outputs re*uired' values to be stored /if any0' and the processing that needs to be done to get the correct outputs. Stage 3: Propose and evaluate possible solutions Dere identify solutions to the problem and evaluate each option to see #hich is most appropriate and choose the best option. Stage 4: Develop and represent an algorithm "n this stage' brea( do#n the problem into simple manageable steps called algorithm so that they can be handled easily. Stage !: )est and validate the algorithm Dere' chec( the algorithm #ritten using some values to ensure that it produces the re*uired results. Stage A: "mplement the algorithm "n this stage' #rite the steps of algorithm using a programming language so that computer can operate on it. 2. :.C diagrams can be used to brea* down a problem into its components. a. #tate what is meant by ?:.C diagrams@ b. 6reate an :.C chart for the following problem statement% ?,ccept the values of length and width of a rectangle and calculate its area@

A. a. An "P. diagram is a table #ith three columns sho#ing the input' output and processing parts of the problem. b. "nput length and #idth Processing Accept length and #idth 1alculate area Store results in area Display area output Area

3. a.

#tate the difference between% i. constants and variables ii. integer data type and floating point data type iii. character data type and string data type b. -efine the following terms% i. identifier ii. literal A. a. i. ?6onstants are fixed values while variables identify a memory location that is capable of storing values that can be changed.@ ii. "ntegers are #hole numbers' positive or negative #ithout decimal places' e.g. ,4!' and 412A% floating point or real numbers are positive or negative numbers #ith decimal values' e.g. ,!.A and 4A.=. iii. 1haracters are anything that you can (ey in from a (eyboard such as letters' numbers and special characters% string is a linear group of characters to be stored as one. b. i. "dentifier is the name used for identifying a variable or a constant. ii. ;iterals are constants that are #ritten literally as itself rather than as a value.

!. 6reate a narrative algorithm that will prompt the user to enter two numbers and find their difference. A. Step 1: Start Step 2: 2et t#o numbers Step 3: Subtract second number from the first number Step 4: Store the results in difference Step !: Display difference +. Write a pseudocode that prompts the user to enter a value and display its s1uare and cube values. A. Step 1: start Step 2: read num Step 3: s*uare num - num Step 4: cube num - num- num Step!: #rite s*uare' cube Step A: stop ;. -raw a flowchart and write a pseudocode that will prompt the user to enter two numbers and display their product. A.
start

read n1'n2

prod 6 n1 - n2

#rite prod

stop

<. Dou need to calculate the area of rectangle using its length and width. -raw a flowchart and write a pseudocode that will accept the length and width and calculate and print the area of the rectangle. Earea > length F widthG A.
start

read length' #idth

area 6 length - #idth

#rite area

stop

Step 1: start Step 2: read length' #idth Step 3: area length - #idth Step 4: #rite area Step !: stop =. Write a pseudocode that will accept 2+ integers and displays the number of positive and negative numbers. A. Step 1: start Step 2: poscount 7' negcount 7 Step 3: for i 1 to 2! Step 3: read num

Step 4: if num<7 then poscount 6 poscount 41 else negcount 6 negcount 41 endif Step !: endfor Step A: #rite poscount'negcount 5. a. -raw a trace table for the following algorithm% b. What is printed by the algorithm x > 12 y > 22 3>+ x > x7y y > x4y 3 > 37x x >y y >3 3>x print x) y) 3 A. a. & 17 27 ! 37 17 3! 17 3! 17 b. )he algorithm #ill print 17 3! 17 y ?

12. a. -raw a trace table for the following algorithm. b. What is the output of this algorithm x > 12 y > 1+ 3 > 22 x> x7y y > x73 3 > x7y73 if x 9y then x > x 7+ else x >xB3 endif

if y 83 then y > y712 else y > y B 12 endif print x) y) 3 A. a. & 17 1! 27 2! 4! B7 22 !! b. )he output #ill be 22 !! B7 y ?

Sample exam questions and answers


'uestion 1 a. Why is it important that you test and validate an algorithm before you convert it into a program b. , form of testing and validating algorithm is by des( chec(ing. What is Hdes* chec*ingI c. What does the implementation stage of problem4solving using a computer involve d. #tate the difference between des* chec*ing and running the program. &uggested ans(er a. /o ensure that the algorithm would produce re1uired results. b. -es* chec*ing is manually going through an algorithm with a set of different values to see if it will produce the re1uired results. c. :n the implementation stage) the steps of algorithm are written using a programming language so that a computer can operate on it. d. -es* chec*ing an algorithm is done manually on paper before converting it into programming language instructions. Junning is done using a programming language after converting the algorithm into programming language instructions.

'uestion 2 a. 6lassify the following as constants or variables. i. + ii. HxI iii. m iv. H2I v. *ey vi. sum vii. 23 viii. 5!.! ix. H2!.3I

x.

HtomI

b. #uggest a suitable data type Einteger) floating point) character or stringG for the following% i. 12.+ ii. 3! iii. HhelloI iv. HcI v. H33+I vi. !+.! vii. 5+ viii. HKac*I ix. 2+.!5 x. HmI &uggested ans(er a. i) constant ii. constant iii. variable iv. constant v. variable vi. variable vii. constant viii. constant ix. constant x. constant b. i. real or floating point ii. integer iii. string iv. character v. string vi. real or floating point vii. integer viii. HKac*I string ix. real or floating point x. character

'uestion 3 Write a pseudocode algorithm that will create a conversion table to convert degrees 6elsius to degree (ahrenheit. .rompt the user to enter the temperature in degree 6elsius and display the temperature in (ahrenheit. E(ahrenheit > 327 E5F6elciusA+G &uggested ans(er #tep 1% start #tep 2% write ?Enter the temperature in degrees 6elcius.@ #tep 3% read 6elsius #tep !% (ahrenheit 32 7 E5F celciusA+G #tep +% write ?/he temperature in (ahrenheit is%@ #tep ;% write (ahrenheit #tep <% stop

'uestion 4 "et salaries of employees are paid after the calculation of their deductions and allowances. /he following rates are used for calculating these allowances and deductions. ,llowances LJ, 1+0 of &asic -, 120 of &asic E, +0 of &asic /, 120 of &asic -eductions ## <0 of &asic Levy 10 of &asic

:n order to calculate the $ross salary the following formulas are used% $ross salary > &asic salary7 allowances "et salary > $ross salary 4 deductions Write a pseudocode that will prompt the user to enter the name and basic salary of an employee and output their name) basic salary) allowances) deductions) gross salary and net salary with appropriate labels. &uggested ans(er #tep 1% start #tep 2% write ?Enter name.@ #tep 3% read name #tep !% write ?Enter basic salary.@ #tep +% read basic #tep ;% hra basic F .1+ #tep <% da basic F.1+ #tep =% ea basic F .2+ #tep 5% ta basic F .12 #tep 12% ss basic F .2< #tep 11% levy basic F .221 #tep 12% allowances hra 7 da7ea7ta #tep 13% deductions ss 7 levy #tep 1!% grossMsal basic 7 allowances #tep 1+% netMsal grossMsal B deductions #tep 1;% write name) basic) allowances) deductions) grossMsal) netMsal #tep 1<% stop

'uestion 5 Write a pseudocode algorithm that will accept two numbers and find their sum and difference. :f the sum is more than sum than the difference) display the sum otherwise display the difference. &uggested ans(er step 1% start step 2% write ?Enter two numbers.@ step 3% read num1)num2 step !% sum num17num2 step +% diff num1B num2 step ;% if sum9 diff then write sum else write diff endif step <% stop 'uestion " 6lassify the following as a relational operation) an arithmetic operation) or a logical operation. a. ,9& or ,96 b. , 89 & c. 6 > , d. N7" e. K 9> 12 f. O>12 and N> 12 g. / F " h. KAO7. &uggested ans(er a. b. c. d. e. f. g. h. logical relational relational arithmetic relational logical arithmetic arithmetic

'uestion # /he following are some terms used in writing algorithms using pseudocode. 6lassify them as input statement) output statement) selection statement) assignment statement) bounded iteration statement) or unbounded iteration statement. a. store b. display c. while4endwhile d. for4endfor e. repeat4until f. read g. if4else h. write &uggested ans(er a. b. c. d. e. f. g. h. assignment statement output statement unbounded iteration statement bounded iteration statement unbounded iteration statement input statement selection statement output statement

'uestion $ /he following are some symbols used in flowcharts. a. b. c. d. e. f. "ame each symbol and give its purpose. &uggested ans(er

a. :nputAoutput symbol EparallelogramG B used to indicate the input and output of the problem. b. /erminator symbol EovalG B used to indicate the beginningAending or startAstop of a problem. c. -ecision symbol Erhombus or diamondG B used in ma*ing a decision between two options) e.g. yes or no. d. 6onnector symbol Esmall circleG B used to connect sections of a flow chart when a flow chart is long and cannot fit on one page. e. .rocess symbol ErectangleG B used to indicate processing Eassignment) calculations) etcG. f. (low control EarrowG B used to show the flow of control of steps.

'uestion ) a. Write a pseudocode that will accept a value for an integer and display the message ?positive@ or ?negative@ based on the integer entered. b. 'sing the pseudocode created) draw a flowchart. a. #tep 1% start #tep 2% read num #tep 3% if num9 2 then write ?positive@ else write ?negative@ endif #tep !% stop b. start

read num

No

is num>0

Yes

Write negative

Write positive

stop

'uestion 1* -raw a flowchart that will prompt the user to enter a number and a character. :f the character is ?#@ the program will display the #1uare of the numberP if it is ?6@ it will display the 6ube of the number. &uggested ans(er start

write enter number

read num

s#uare num $ num cube num $ num $ num

write enter character( or !"

read char

Yes is char = write s#uare Yes

No

is char = !

No

write cube

write inva%id character

stop

Programming +anguages
Chec !our progress 1 1. List /WC advantages and C"E disadvantage of high4level languages over machine4level languages. A. Advantages: 9asy to read' #rite and understand% easy to correct mista(es% portable as they are machine independent Disadvantages: slo#er in e&ecution as translation re*uired 2. Natch the following program instructions with their corresponding language% :nstruction .rogramming Language a. #CJ/ #/C6O &D :/EN",NE i. Ligh4level b. #'& ,) & ii. Nachine4level c. .J:"/ #'N iii. !$L d. 121221121 iv. +$L e. $E/ NE /LE L,J$E#/ "'N&EJ v. ,ssembly4level A. a. iii b. v c. i d. ii e. iv 3. , machine4level language program runs on one type of computer) but not on another type of computer. Why A. +ecause they are machine,dependent. !. -efine the following terms% a. program b. assembler c. !$L A. a. A set of instructions #ritten in a programming language that directs the computer to solve a problem or tas(. b. A translator that converts assembly level language into machine level language.

c. A programming language #here the programmer ust has to specify #hat is to be attained instead of giving steps for ho# to attain it. +. Ligh4level languages also need translators to convert to machine level. $ive /WC types of translators used by them. A. 1ompilers and interpreters. Chec !our progress 2 1. List the five stages involved in program implementation. A. 1reating source code' compiling' lin(ing' e&ecuting and maintaining. 2. #tate the difference between source code and obQect code. A. A program in high,level or assembly,level language is called a source code and a program in machine,level language is called ob ect code. 3. -efine the terms% a. /esting b. -ry run c. /est data A. a. ;oo(ing for errors in the program and ma(ing sure that it is #or(ing properly. b. Eanually going through program statements one by one' loo(ing for errors. c. )he input values used to see if the program produces re*uired results. !. List three tas*s involved in debugging a program. A. ;oo(ing for errors' locating errors' correcting errors. +. What are the three different types of program errors A. Synta& error' logic error and run time error. ;. -istinguish between syntax errors and logic errors. A. Synta& errors are errors reported by translators #hen the rules of the programming language are not follo#ed correctly% logic errors occur #hen the re*uired results of a program cannot be produced due to the incorrect logic of the programmer. Chec !our progress 3 1. Dou are writing a program to find the average of three integers. /he average is stored in a variable named avg. What is the data type for the variable avg $ive a reason for your answer. A. )he data type of variable avg #ould be real as it can possibly have decimal places. 2. Write a statement to declare the variable avg. A. var avg:real 3. Dou need to initialise the variable avg to 3ero at the beginning of the program. Write the .ascal statement to do this. A. avg :67

!. Which of the following are valid variable names % a. !you b. Mall c. date of birth A. a. Fo b. Ges c. Fo +. 6onsider the following program and identify all the errors. program calcP const no %> 2 a) b) c% integerP begin c% > 2 a %> +P b %> 12.<+% c % > no 7 b 7cP end. A. "n program line 4' the (ey#ord var is missing in front of variable declaration. "n program line !' the value of b has decimal places so the variable declaration at line 4' must be real instead of integer. Chec !our progress 4 1. What is displayed by the following statements if the user enters 12 WriteEHEnter your years of service%IG JeadEyrsGP A. 9nter your years of service: 2. What is printed by the following two statements WriteEHLelloIGP WritelnEHEveryoneIGP A. Dello9veryone 3. What is the value of E3; div +G F E3+ mod !G A. =-3 621 !. Write an algorithm and a program to compute the V,/ payable on an item. /he program should as* the user to enter the price of an item and compute the V,/ payable on the item using a fixed rate of 1;0 of the price. A. program discount% const rate :6 .1A var vat' price: real% begin #riteln/H9nter the priceI0 % readln/price0% vat :6 price- rate% #rite/vat0%

end. Chec !our progress 5 1. , store uses the following policy to award discount. :f the customer purchases products costing more than R+22 she is given a discount of 120) otherwise she is given a discount of 20. Write a program to compute the discount a customer will receive based on the purchase she ma*es. A. program discount% const rate1 :6 .17 const rate2 :6 .72 var discount' price: real% begin #riteln/H9nter the priceI0 % readln/price0% if price<!77 then discount :6 price- rate1% else discount:6 price -rate2% #rite/vat0% end. 2. Write a program to print the message HDour tuition is wavered@ if the student scores over =+ mar*s in the entrance examination. program tuition% var score: integer% begin #riteln/H9nter scoreI0% readln/score0% if score<@! then #riteln/HGour tuition is #averedI0% end. 3. 6onsider the following while loop%
&egin a %> 2P while a 8 + -C begin a %> a 7 3P WritelnEa) Sis less than +SGP end; end. How many times would the program go through the loop?

A. The program will go through the loop two times.


!. 6onsider the following segment of code% &egin for a %> 1 to + do WritelnESLelpSGP WritelnESmeIGP end. Is the above statement correct? Give reason for your answer.

A. No. The two Writeln statements should be between a begin and end statement. The correct code is:

begin For a:= 1 to 5 do begin Writeln( elp!"# Writeln(me!"# end# end.


+. 6onsider the following segment of code% &egin a %> 2P repeat a %> a 7 1P Writeln( he number is ! a"; until a 9 +P

8End computer font9


:n the third repetition of the repeat4until segment) what is printed out

A. "t #ill print 3.


Chec !our progress " 1. 6onstruct a trace table for the following segment of code% &egin a %>1P b %> 2P c %> 1P while a 8 22 -C begin b %> a F 2P c %> b 7 1P a % > c 7 2P endP end.

A.
A 1 B 2 2 3 ! 17 11 13 27 21 23 C 1

2. 6onsider the following lines of code% a %> 1P b %> a B 1P c %> a div bP What type of error would be generated when the three statements above are executed $ive a reason for your answer.

A. $un%time error due to di&ision b' (ero.

3.

, program has been tested and all errors are corrected. What type of errors could still occur when the program is executed A. )ogical errors

Chec !our progress # 1. List three advantages of proper documentation in a program. A. 1lear documentation ma(es it easier for users to comprehend and use the program% if there is a problem #ith a section of the program' users can refer to the documentation to solve it% users and programmers can easily ma(e a modification to the program. 2. #tate the difference between internal and external documentation A. "nternal documentation is documentation that appears inside a program in the form of comments that ma(e the reading and understanding of the program easier. 9&ternal documentation is documentation that is developed separately and supplied #ith the program' #hich acts as a guide for the program users. 3. (or each of the following) classify them as internal documentation or external documentation. a. Neaningful variable names b. (re1uently ,s*ed Tuestions c. /utorial d. :ndentation e. /abs A. a. "nternal b. 9&ternal c. 9&ternal d. "nternal e. "nternal !. What is technical documentation A. )echnical documentation contains the technical aspect of program such as its version' the operating system that it can #or( #ith' the amount of memory and hard dis( space re*uired' and the installation procedure. +. Nost programs come with user documentation. What are the typical contents of user documentation A. "nstructions li(e ho# to: start or stop the program' move around different parts of the program and solve simple program errors. End-of-section questions %ultiple-choice 1. Which one of the following is a low4level language% , LLL & ,LL 6 !$L - +$L A. + 2. Which one of the following is not a feature of third generation languages , they need to get translated

& they are faster than NLLs 6 they are easy to use than NLLs - they use compilers and interpreters A. + 3. /he translator used by second generation languages is% , compiler & lin*er 6 assembler - interpreter A. 1 !. /he following are steps associated with implementing the program :. compiling ::. create source code :::. lin*ing :V. maintain program V. executing /he correct order is% , :) ::) :::) :V) V & ::) :) :::) V) :V 6 ::) :) V) :::) :V - ::) V) :) :::) :V A. + +. /he error that occurs when the program has to stop before its completion due to a bad condition such as division by 2 is% , debug error & syntax error 6 logic error - run4time error A. D ;. Which of the following is not a data type found in .ascal , integers & real 6 text - string A. 1 <. ,n example of a conditional branching statement in .ascal is% , goto & if Bthen 6 for - while A. +

=. /he following are loop statements used in .ascal except% , while & if4then 6 for - repeat A. + 5. /he maQor advantage of machine4level languages over other programming languages is% , they are slower in execution & they are slower in correcting mista*es 6 they are faster in execution - they are faster in correcting mista*es A. 1 12. .rogramming languages that use mnemonics are called% , machine4level languages & high4level languages 6 assembly4level languages - fourth generation languages A. 1 &tructured questions 1. a. #tate the difference between first generation and second generation languages. b. List one advantage and two disadvantages of first generation languages compared to second generation languages. c. List three examples of third generation languages. A. a. 8irst generation languages or machine,level languages use binary code% second generation or assembly,level languages use mnemonics. b. Advantage: )hey are faster in e&ecution than second generation Disadvantages: hard to read' #rite and understand% hard to correct mista(es% machine dependent c. Pascal' +AS"1' 1' 8.3)3AF 2. a. List the se1uence of steps associated with implementing a program. b. #tate the difference between% i. testing and debugging ii. syntax error and logic error iii. logic error and run4time error iv. testing and dry running c. -efine the term Htest dataI. A. a. 1reating source code' compiling' lin(ing' e&ecuting' maintaining. b. i. )esting is ma(ing sure that a program does not have any errors and is #or(ing properly% debugging is loo(ing for errors' locating and correcting them. ii. Synta& errors are errors reported by translators #hen the rules of the programming language are not follo#ed correctly% logic errors occur #hen the re*uired results of a program are not produced due to the bad reasoning of the programmer.

;ogic errors occur #hen the re*uired results of a program are not produced due to the bad reasoning of the programmer% run,time errors occur #hen the program has to stop before its completion due to a #rong condition. iv. )esting is ma(ing sure that a program does not have any errors and is #or(ing properly using the programming language% dry running or des( chec(ing is manually going through the program one statement at time' loo(ing for errors before it is entered into the computer system. c. )est data are values used in a program to determine if it produces the re*uired results. 3. a. b. c. A. #tate one conditional branching statement in .ascal. #tate one example of a bounded iteration statement in .ascal. #tate one example of an unbounded iteration statement in .ascal. a. if,then,else b. for c. #hile

iii.

!. , well documented program ma*es it easy for the user to use. a. List two types of program documentation. b. #tate the purpose of each documentation you identified in your answer to T!a A. a. "nternal and e&ternal. b. "nternal documentation is used to ma(e the reading and understanding of the program easier. 9&ternal documentation is documentation that acts as a guide for the program users. +. 'sing the algorithm you created for T1+ in #ection 2Is End4of4section Tuestions) write a program in .ascal that prompts the user to enter a value and display its s1uare and cube values. A. program s*uareJcube% var num' s*uare' cube: integer% begin #riteln/H9nter numberI0 % readln/num0% s*uare :6 num- num% cube :6 num-num-num% #riteln/Hthe s*uare isI' s*uare0% #riteln/Hthe cube isI' cube0% end. ;. 'sing the flowchart you created for T1; in #ection 2Is End4of4section Tuestions) write a program in .ascal that will prompt the user to enter two numbers and display their product. A. program product% var num1' num2'product: integer% begin #riteln/H9nter first numberI0 % readln/num10% #riteln/H9nter second numberI0% readln/num20% product :6 num- num% #riteln/Hthe product isI' product0%

end. <. 'sing the flowchart you created for T1= in #ection 2Is End4of4section Tuestions) write a program in .ascal that will accept 2+ integers and displays the number of positive and negative numbers. A. program positiveJnegative% var num' s*uare' cube: integer% begin for i :6 1 to 2! do begin readln/num0% if num<7 then poscount6poscount41% else negcount6negcount41% end% #riteln/Hnumber of positive numbers isI' poscount0% #riteln/Hnumber of negative numbers isI' negcount0% end. =. a. Write a pseudocode that will accept a set of mar*s of students and display the /he pseudocode stops when the user input 41 for mar*s. b. 'sing the pseudocode you created in your answer T=a as a guide) implement .ascal. A. a. Step 1: start Step 2: largest 7 Step 3: read num Step 4: #hile num >< ,1 "f num<largest then largest num endif read num end#hile Step !: #rite largest Step A: stop b. program highest% var i' num' mar(: integer% begin largest :6 7% readln/Henter numberI0% read/num0% #hile num> <,1 do begin "f num<largest then largest 6num% readln/Henter numberI0% read/num0% end% end. highest mar*s. the program in

5. a. Write a pseudocode that will accept scores of 33 batsmen in a cric*et tournament and display the number of batsmen who scored 2 and the number who scored more than 2. b. 'sing the algorithm you created in your answer to T5a as a guide) implement the program in .ascal. A. a. Step 1: start Step 2: ?erocount 7 Step 3: non?erocount 7 Step 4: for i 1 to 33 read runs "f runs<7 then non?erocount non?erocount 41 else ?erocount ?erocount 4 1 endif endfor Step !: #rite ?erocount' non?erocount Step A: stop b. program runs% var i' runs' ?erocount' non?erocount: integer% begin ?erocount :6 7% non?erocount :67% for i :61 to 33 readln/Henter runs of batsmenI0% read/runs0% begin "f runs< 7 then non?erocount :6 non?erocunt 41% else ?erocount:6 ?erocount 41% end% end. 12. Write a program in .ascal that will read sales of +2 sales men into an array and display the sales of all sales men who have total sales more than R12)222. A. program sales% var i: integer% scores: K1 to !7L of integer% begin #rite/HStoring sales in an arrayI0 for i: 6 1 to !7 do begin #rite/H9nter salesI0% readln/salesKiL0% end% #rite /H3eading sales from the array and chec(ing for sales<1777I0 for i: 6 1 to !7 do begin

if salesKiL <1777 then #riteln/salesKiL0% end% end.

Sample exam questions and answers


'uestion 1 $ive appropriate programming terms for the following% a. Errors reported by translators when the rules of the language are not obeyed. b. , program in high4level or assembly4level language. c. ,n error in a program. d. When the re1uired results are not given by the program due to bad reasoning by the programmer. e. :nput values used in a program to see if it is producing the correct results. &uggested ans(er a. #yntax error b. #ource code c. &ug d. Logic error e. /est data

'uestion 2 a. Write one program instruction in each of the following types of programming languages% i. Ligh4level language ii. Nachine4level language iii. ,ssembly4level language iv. !$L v. +$L b. "ame the translator used for the following% i. /o convert LLL instructions to NLL by ta*ing one instruction at a time. ii. /o convert ,LL instructions to NLL. iii. /o convert LLL instructions to NLL by ta*ing instructions together. &uggested ans(er a. i ii. iii. iv. v. b. i. interpreter ii. assembler iii. compiler .J:"/ #'N 122112111 N'L , by & #ort file1 by lname $ive me the total price of all items purchased

'uestion 3 a. /he following are some control structure statements used in .ascal. $ive the type of control structure for each statement. i. for ii. while iii. if4then4else iv. repeat v. if4then b. List four operations that can be performed on an array. &uggested ans(er a. i. bounded iteration ii. unbounded iteration iii. selection iv. unbounded iteration v. selection b. Jead) write) traverse and search.

'uestion 4 Write a program in .ascal using the following algorithm% a. .rompt the user to enter a number. b. ,ccept the value and store it in variable num. c. 6hec* to see if num is more than 12. :f it is more than 12 add + to it. Ctherwise multiply num by 3. #tore the results in a variable ,ns. d. -isplay the results in ,ns along with the message ?the answer is@. &uggested ans(er .rogram calculationsP Var num) ans% integerP &egin WritelnEHenter a numberIGP JeadlnEnumGP :f num912 then ans%> num7+ else ans%> numF3P writelnEHthe answer isIGP writeEansGP End.

'uestion 5 /he following shows parts of a computer program. #uppose .art , shows the program before translation and .art & shows the program after translation. Part , JeadlnEnum1GP JeadlnEnum2GP #um %> num17num2P WritelnEsumGP a. b. c. d. e. Part 12212211211 11112211121 11211212112 11211221112

Which generation or level language is .art , Which generation or level language is .art & "ame one translator that can be used to convert .art , to .art &. What is the generic name for the program code in .art , before translation What is the generic name of the program code in .art & after translation

&uggested ans(er a. b. c. d. e. Ligh4level or 3rd generation language Nachine4level or 1st generation language 6ompiler #ource code CbQect code

'uestion " Write a program in .ascal that will accept the values for .rincipal) "o of Dears and :nterest Jate) then calculate and display the simple interest. E#imple :nterest > .rincipal F DearsFJate A122G &uggested ans(er .rogram simpleinterestP 'ses crtP Var siMintrst) principal) years) rate%real begin clrscrP writelnEHenter the .rincipal ,mountIGP readlnEprincipalGP writelnEHenter no of yearsGP readlnEyearsGP writelnEHenter rateIGP readlnErateGP siMintrst %> principal F years F rateA122 writeln E Hthe simple interest isIGP write EsiMintrstGP end.

'uestion # Write a program in .ascal that will prompt the user to enter three une1ual numbers and display the smallest among them. &uggested ans(er program smallestP uses crtP var num1) num2) num3) smallest %integerP begin clrscrP writelnEHenter first numberIGP readEnum1GP writelnEHenter second numberIGP readEnum2GP writelnEHenter third numberIGP readEnum3GP if num18num2 then smallest %> num1 else smallest %> num2P if num38smallest then smallest%> num3P writelnEHthe smallest number isIGP writeEsmallestGP end.

'uestion $ Write a program in .ascal that will print the even numbers between 122 and 322. &uggested ans(er program evenMnumbersP uses crtP var i% integerP begin clrscrP for i %> 122 to 322 do begin if i -:V 2>2 then writelnEiGP endP end.

'uestion ) Write a program in .ascal that will accept a number and display the multiplication table of that number up to 22 times in the following format % 1x+>+ 2 x + > 12 3 x + > 1+ UU UU UU UU UU UU UU 22 x + > 122 &uggested ans(er program multiplicationMtableP uses crtP var i) prod) num% integer begin clrscrP writelnEHenter number for multiplication table re1uiredIGP readlnEnumGP for i%> 1 to 22 do begin prod > i F numP writelnE i) HxI) num) H>I) prodGP endP end.

'uestion 1* Write a program in .ascal that will accept 32 mar*s of students and display the number of students who scored =2 or more) ;2 4<5 and below ;2. &uggested ans(er

program gradeMcountP uses crtP var score)aMcount)bMcount)cMcountP begin aMcount%> 2 bMcount%> 2 cMcount%> 2 writelnEHenter scoreIGP readlnEscoreGP while score8 9 41 do begin if score9>=2 then aMcount%> aMcount71P if score9>;2 and score 8=2 then bMcount%> bMcount71P if score 8;2 then cMcount %> cMcount71P writelnEHenter scoreIGP readlnEscoreGP end. writelnE?number of students who scored =2 or more is GP writeEaMcountGP writelnE?number of students who scored between ;24<5 is GP writeEbMcountGP writelnE?number of students who scored below ;2 is GP writeEcMcountGP end.

Common mistakes Hints and tips


Problem-solving and Program Design and Programming +anguages
:t is bad practise to write a program without creating an algorithm first. &y creating algorithms) you can wor* out the steps for solving the problem. #ome people create algorithms after writing programs which is a waste of time. When algorithms are to be represented using flowcharts) ma*e sure that the symbols used are correct. Jeal4time processing and online processing are different. When writing algorithms -C "C/ use actual values in place of variable names. (or example) if the 1uestion is to read three numbers) the statement should be written as Jead num1)num2)num3 not Jead 3)!)+. :t is important that you use the correct loop statement% if the 1uestion has statements li*e H1 to ")I H122 numbersI) etc. use the (CJ loopP if the 1uestion has statements li*e Ha set of numbersI) Ha group of numbersI) Hterminated by 2I) Hstopped by 41I) etc. use the WL:LE loop or the JE.E,/ loop. Na*e sure you use the correct logical operator. Nany students mix up the 9 and 8 signs. Jemember that the 9 sign is for Hgreater thanI and the 8 sign is for Hless thanI. Jemember that when you are using trace tables) when a new value comes in) the old value is replaced by the new value.

When an output statement is inside the loop) you will have outputs for every time that the loop executes. When an output statement is outside the loop) you will only have one output. Jemember you N'#/ declare all variables and constants before their use. ,s a beginner programmer) ma*e sure you practice well4documented programs with meaningful variable names) indentation) comments) etc.

Revision flashcards Problem-solving and Program Design


Problem-solving &tage 1 /he stages of general problem4solving are% -efine the problem ,nalyse the problem #uggest possible solutions Evaluate and choose the best solution :mplement and review Problem-solving &tage 2 /he stages of problem4solving using computers are% Problem-solving &tage 3 ,nalysing the problem involves brea*ing down the problem into inputs) processing) storage needed and outputs. ,n :.C diagram can be used to brea* down the problem -efine the problem ,nalyse the problem #uggest possible solutions and choose the best solution 6reate algorithm /est and validate the algorithm :mplement the algorithm in a programming language to become a program Jun the program -ocument and maintain the program

.ariables/ Constants/ +iterals and Data 0!pes Variables are identifiers of storage locations in memory that can store any value. 6onstants are fixed values. Literals are constants that are written literally in a program -ata types determine the type of data a variable can store /he data types are% integers) floating point) characters and string.

,lgorithms #tep4by4step definition of a tas* or problem /he characteristics of algorithms are% precise) unambiguous) finite steps) terminate. /he ways to represent algorithms are% narrative) pseudocode and flowchart

1a!s to 2epresent ,lgorithms 1 "arrative B instructions are written in plain English. .seudocode B instructions resemble programming language instructions (lowchart B diagrammatic representation of algorithms using special symbols

1a!s to 2epresent ,lgorithms 2 WordsAphrases used in pseudocode% for accepting data use read and input for storage use store and for output use #rite' output' display

Program Constructs or Control &tructures /hree types B se1uencing) selection and iteration. #e1uencing is putting instructions in the order it should ta*e place #election is ma*ing a choice between two or more options by using the decision ma*ing capabilities of computer #election statements used in pseudocode are if4then) if4then4else Jepetition or iteration is used to repeat a certain process a number of times :teration or loop statements used in pseudocode are for4endfor and while4 endwhile.

#ymbols used in flowcharts% Cval B inputAoutput or terminal symbol Jectangle B processing Jhombus or diamond B decision ,rrows B flow of control #mall circles B connectors for sections of flowchart

Revision Flashcards
Section 2 Problem-solving and Program Design
Dou can use these blan* cards to create your own revision flashcards.

Revision flashcards
Section 3 Program Implementation

Programming +anguages 'sed to communicate with the computer 6an be broadly classified as low4level and high4 level Low4level languages are close to machine language Ligh4level languages are close to English language (ive generations of programming languages

3enerations of Programming +anguages (irst generation or Nachine4level language uses binary #econd generation or ,ssembly4level language uses mnemonics /hird generation or Ligh4level language uses English4li*e instructions (ourth generation or !$L also English4li*e instructions where programmer Qust has to specify what is to be attained instead of giving steps for how to attain it (ifth generation language or +$L uses natural language instructions in a conversational way /here are advantages and disadvantages of each generation of programming languages

0ranslators used in Programming +anguages "o translators needed for NLL /ranslator for ,LL is assembler /ranslators for LLL are compiler and interpreter

&teps in 4mplementing a Program 6reating source code 6ompiling Lin*ing Executing Naintaining

6ompilers produce an executable code and interpreters do not produce any executable code.

Jevise definitions of terms used in programming% testing debugging syntax errors logical errors run4time errors dry run test data

Programming in Pascal 1 .rogram structure in .ascal #teps in creating program) compiling and executing a program using a .ascal compiler -ata types used in .ascal language% o o o o integers real character string

Programming in Pascal 2 -eclare variables and constants Write programs using se1uence control structure in .ascal with arithmetic operators and assignment operator E%>G Write programs using selection control structure in .ascal Euse of if4then and if4then4else statementsG Write programs using iteration control structures in .ascal Euse of for) while and repeat statementsG

Programming in Pascal 3 ,rrays or lists used for storage and retrieval of data of same data type Cperations on arrays B reading) writing) traversing and linear searching Write programs showing how readingAwriting is performed in an array Write programs showing how traversing is carried out in an array Write programs showing how linear search is carried out in an array

Programming in Pascal 4 /est programs for correctness using appropriate test data /esting involving correct and incorrect data values to see the program would wor* for both values -ocumentation of programs% internal and external documentation :nternal documentation involves meaningful variable names) comments) indentation) etc. External documentation such as user manuals

Revision Flashcards
Section 3 Program Implementation
Dou can use these blan* cards to create your own revision flashcards.

You might also like