0% found this document useful (0 votes)
12 views

7problem Solving and Program Design

This document provides comprehensive notes on problem solving and program design aligned with the CSEC syllabus for the 2021 Information Technology exam. It outlines the steps in problem solving, including defining the problem, proposing solutions, developing algorithms, and testing solutions, while also explaining key concepts such as variables, constants, data types, and algorithms. Additionally, it covers input/output instructions, performing calculations, and selection statements in programming.

Uploaded by

eloiserivers15
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

7problem Solving and Program Design

This document provides comprehensive notes on problem solving and program design aligned with the CSEC syllabus for the 2021 Information Technology exam. It outlines the steps in problem solving, including defining the problem, proposing solutions, developing algorithms, and testing solutions, while also explaining key concepts such as variables, constants, data types, and algorithms. Additionally, it covers input/output instructions, performing calculations, and selection statements in programming.

Uploaded by

eloiserivers15
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

2

Problem
S
o
l
v
i
n
g
Ms D
B
r
0
2
a
o
n
w
d
n
e
P

1
r
o
g
r
a

E
m

D
e
This booklet contains notes related to Problem
Solving and Program Design. The notes
follow the CSEC syllabus for the 2021
Information Technology exam.

CSEC IT Class
June 2021 Sitting
1-869-661-2282
[email protected]
SPECIFIC OBJECTIVES
1. Outline the steps in problem solving

Problem – Anything you are trying to solve computationally. Problems usually


specify an input and a desired output.

Problem solving – Understanding how a human solves a problem then


transferring that understanding into something a computer can do. This is done
by writing the specific syntax, that is required by the computer, to get the job
done.

In problem solving, there are a series of steps that are required in order to
achieve a solution.

1. Define the problem


During this step, you are expected to define the problem in your own
words. Outline the intended outcome of the problem. Identify the data
that is required as input and the information needed for the intended
output. The problem should not leave you or anyone else unsure of what
is required.
2. Propose and evaluate solutions
Look for patterns when solving your problems. Examine related
problems, and determine if the same technique can be applied. Examine
a simpler or special case of a problem to gain insight into the solution of
the original problem. Look for various ways in which the problem can
be solved.

3. Determine the most efficient solution


This step involves selecting the best solution. Think about the time it
takes to solve the problem, required computer memory and the
efficiency of the solution.

4. Develop the algorithm


Use your most efficient solution and create some clear and concise steps
to follow that will help you to arrive at your solution. You can also
draw a diagram outlining the steps to follow. Include error messages for
data that is not expected when accepting input and during processing
that might cause the program to crash.

5. Test and validate the solution


Your solution must be tested in order to determine its correctness. Work
the problem by hand (with a calculator or by using a trace table) for a
specific set of data.
2. Use the divide-and-conquer approach to decompose large everyday
problems into smaller tasks

This is taking one large complex problem and strategically breaking it into
smaller simpler problems. The smaller simpler problems can be solved much
easier on their own. After these smaller tasks are solved, their solutions are
combined which would ultimately result in solving the large complex problem.

Example
If I take 10 cards, each with a letter and in random order, and turn them down
on a desk, would you be able to find letter "L" quickly?

However, if I take these same 10 cards, arrange them in ascending order and
turn them down on the desk, would this make it easier to find letter "L"?

What strategy would you utilize to find letter "L" after choosing the first card?

You may probably have said that after choosing the first letter, maybe card 4
which was "F", you would choose a higher card since the cards are arranged in
ascending order. And thereafter, you would choose a lower card if the letter was
after "L" and using this technique, you will gradually find letter "L".

By taking what may initially seem to be a difficult task and breaking it up into
smaller parts and using a variety of strategies, it becomes easier to find a
solution, in this case, the letter "L".
3. Define a problem by decomposing it into its significant components
Defining the problem involves a problem statement (a clear definition of the
problem that needs to be solved). The problem statement must then be broken
down into its main components

 Inputs – the data you are provided with or have to obtain from the user.
Some words that help you identify the inputs are: read, input, enter,
given, accept.

 Outputs – The results that should be produced. Some words that help
you identify the outputs are: print, calculate, output, display.

 Processing – The tasks that must be performed. In other words, what


must be done to the inputs in order to arrive at the outputs.

 Storage – the data that must be stored.

We can illustrate the main components of a problem by using a defining


diagram (IPO chart). This consists of a table with 3 columns: Input, Processing
and Output.
E.g., 1 Write a program that reads two numbers and prints their total

The word read tells us that the input will be in the form of two numbers. The
desired result is the total, so we’ll call the output total. Each task that must be
performed counts a processing. This means that reading the two numbers,
calculating their total and printing the total will all fall under processing

Input Processing Output


Two numbers, say 1. Read two Total
num1 and num2 numbers
2. Calculate the
total
3. Print the total

Input Processing Output


Two numbers, say 1. Read two numbers Total
num1 and num2 2. Add num1 to num2
3. Store the result in
total
4. Print the total

E.g., 2 Read the price of an item and its type. A 5% discount is to be given
on all books. If the item is a CD then there will be a 10% discount. All
other items are to get a 2% discount. Calculate and print both the discount
as well as the discounted price.
Input Processing Output
Item, type 1. Read the item and its type Discount
2. Calculate the discount Discounted price
3. Calculate the discounted price
4. Print the discount and discounted
price

It is important to note the processing steps are not a solution to the


problem.

4. Distinguish between variables and constants


When designing our problems, we need to be able to store our data in the
computer’s memory. Some of the data we have stored will change and some
would remain the same. differentiate between two types of data; variables and
constants.

Variable: an area of storage whose value can change during processing. For
example, name, age, area, month.

Constant: an area of storage whose value cannot change. For example, the
value of pi, the number of months in a year, the number of hours in a day.

Both variables and constants are given names in order to identify them. (these
are referred to as identifiers). It is a good practice to use names that refer to the
type of data that will be entered or stored. For example, age can be used to store
someone’s age and avg can be used to store average.

Rules to follow when thinking of a variable name:


- The name of the variable should reveal what it does
- It should only contain letters, numbers and underscores
- It should begin with a letter
- It must not contain any spaces. If you want to use a space, use an
underscore instead.

Data types – a particular kind of data item, as defined by the values it can take,
and the operations that can be performed on them.
Data types can be divided into three broad categories – textual, numerical and
Boolean
Textual data can include a combination of letters, symbols and numbers. This is
further divided into two categories:

Character – if it is one character. E.g. ‘a’, ‘%’, ‘1’

String – A group of characters. “The red ball”, “name”, “10 lbs.”

Textual data contains things other than numbers, as a result of this, we don’t
perform calculations on textual data.

Numerical data – when it comes to programming, there are two main types of
numbers:

Integers – numbers that don’t have a decimal point. E.g., 1, -3, 200.

Real numbers (floating point) – Numbers with a decimal point. E.g., 6.8, 9.0,
0.56.

Boolean – data that must either be true or false. E.g. is x > 20, is y = 4.

Data Type
The grade a student got in a course character
e.g A, B, C, D, F
The time Usain Bolt takes to run a Real number (floating point)
100 m race
The number of books in a person’s Integer
bag
Whether or not a piece of luggage is Boolean
overweight
The cost of an item in a store Real number (floating point)
A person’s name string

5. Explain the concept of algorithms


An algorithm is a formal sequence of instructions that defines a solution to the
problem.

Characteristics of an algorithm
 It must have a finite number of steps. Algorithms should not go on
forever.

 It must be precise. The steps should be clearly defined and stated.

 It must be unambiguous. An algorithm shouldn’t include


statements that can be interpreted multiple ways.

 It must have a flow of control from one process to another. – The


algorithm should state what order the steps should be completed in.

 It should terminate and give the correct result. At the end of all
the required steps, the algorithm should come to an end and produce
the correct result.

6. Represent algorithms in the forms of flowchart and pseudocode

Pseudocode – An informal high-level representation of the actual code that is


written in plain English. This representation shows how the computer program
will work. Pseudocode is generally understood by all programmers regardless
of the programming language they use.

Data input and storage


In order for the computer to process data, we must first enter the data into the
computer. This data is then stored into the computer’s memory as variables so
that it can be accessed by the computer when necessary. When the computer is
processing data, sometimes it stores some of the results in memory as well.

The Input Instruction


When giving the computer data, the following commands can be used. READ
or INPUT. This is followed by one or more variable names that represents the
data that is being entered or stored. When more than one variable is used, place
a comma between each variable.
Syntax: READ <variable_name>, <variable_name>

Write an instruction to input two ages


Solution: READ age1, age2

Write an instruction to input the price of an item


Solution: READ price

Write an instruction to read three scores


Solution: READ score1, score2, score3

Displaying Information
The output instruction
When a computer has finished processing data, the results are given in some
form of output. Output can be sent to the screen or the printer. Commands that
are used to produce the output are the words PRINT and DISPLAY and
OUTPUT

They can be used to display the value of a variable or to output the data that is
in a constant.

Outputting the value of a variable


When a variable is printed, the variable’s content is printed instead of the
variable’s name. The computer will look for the section in memory that is used
to store the variable. The information that is stored in that segment will then be
printed.
Syntax: PRINT <variable_name>

If more than one variable is to be printed, the variables are separated by a


comma.

The command PRINT sum will print the value that was assigned to sum

Let us assume that A = 10. The command PRINT A will cause 10 to be printed
and not the letter A.

Variables used with the print instruction must not be new variables. They
should be variables that have been executed in an instruction prior to the
PRINT instruction.

Outputting a string constant


A string constant (string literal) are special type of constants which store
fixed sequences of characters. A string constant is surrounded by quotation
marks.

H world
Created by Dianna Browne on March 12th 2022

START
PRINT “Hello world!”
STOP

Prompts
When entering data, messages may appear on the screen notifying the user of
what data is to be entered. These messages are called prompts or captions.
They begin with the word PRINT or DISPLAY, followed by the message
enclosed in quotation marks. Anything written inside the quotation marks
would be displayed as is by the computer.

Example: PRINT ‘Enter the name’

In the above example, “Enter the name” will be displayed on the screen. This
will let the user know the data the program is expecting.
Anything enclosed in quotation marks while using the PRINT command will be
displayed on the screen. PRINT ‘name’ will display the word name.

There will be times when we wish to output a label or an explanation along with
a variable. This can be done with the use of string constants.

Syntax: PRINT <string>, <variable_name>

For example: PRINT ‘Cost’, COST


In the above example, ‘Cost’ is a constant and COST is a variable. The word
‘Cost will be printed as well as the value stored in the variable COST.

In the following example 20.00 is stored in the variable PRICE and ‘Price of an
item:’ is a constant

PRICE = 20.00
PRINT ‘Price of an item:’, PRICE

Hence, ‘Price of an item: 20.00’ is printed

Performing Calculations
Processing data can involve performing calculations on the data given. These
calculations can be done by using arithmetic operators.

Arithmetic operator

A mathematical function that takes two operands and performs a calculation on


them.
Li
Calculations can only be performed on numerical data. This data can be in the
form of variables or constants. The calculation’s result must be stored in a
variable for future use, such as for printing or for use in subsequent calculations.
Syntax: <variable> = <what is being calculated> or <variable>  <what is
being calculated>

E.g. AMTDUE = PRICE * QUANTITY


INCHES = FEET * 12
SUM = FIRSTNO + LASTNO
AVERAGE_AGE  SUM/4
A = Num1
The result of the calculation is stored in the variable to the left of the ‘=’ or the
.
Assignment statement – any statement that assigns a value to a variable. The
value being assigned could be a constant, a variable or a calculation.
For example:
Sum = 0, store 0 to sum, sum 0
a = b, store b to a, a b
grade = ‘A’, store ‘A’ to grade, grade  ‘A’
total = a + b + c, store a + b + c to total, total  a + b + c

Each assignment statement must begin with


1. A variable followed by the assignment operator, then either a variable, a
constant or a calculation

Or

2. The word store, followed by a variable, a constant or a calculation, then the


word to and a variable.

Store a+b+c to sum

Write an algorithm to find the area of a square

Solution
START
PRINT ‘Enter the length’
READ length
AREA = length * length
PRINT AREA
STOP

Write an algorithm to find the amount due given the cost and quantity of
an item

START
PRINT ‘Enter the cost and quantity’
READ cost, quantity
AmtDue = cost * quantity
PRINT ‘The amount due is’, AmtDue

PRINT ‘The amount due is $’ AmtDue  The amount due is $5


STOP

The variable, which begins an assignment statement should not be a variable


that was read as input if the input is to be printed.

Variables used in the formula for calculations must be variables that were used
in executed statements prior to the calculation instructions and not new
variables.

Increasing and decreasing numerical variable values

When you have to increase or decrease the value of a variable, the variable
appears on both sides of the assignment statement.

Example:
count = count + 1
num_left = num_left - 5

Selection statements
When a program is executed, each instruction is
processed in the sequence listed in the program,
unless specific instructions direct it to deviate and
select other instructions.

A selection statement allows a program to test a condition and execute


instructions based on which condition is true. In other words, the program
could skip a line of execution or choose which line it should execute. The
selection statements are the if statements and the case statement.

A condition is made up of three parts. The first part is a variable that was
carried out before. The second part is the relational operator, and the third part
is a variable that was carried out before or a constant.

C = 45 condition using a variable and a constant


C < X  condition using 2 variables
A compound statement is a statement (condition) that comprises of more than
one condition

C = 45 AND C < X
C = 45 OR C < X

Relational operators
These operators test or define some kind of relation between two entities. They
are important for making decisions. These operators take two operands,
compare their values and return their Boolean value (true or false). They are
mostly used in conditional expressions to test whether a condition is true or not.

Conditions can contain data of different data types. When the data of the
condition is the character data type, the data should be enclosed in quotation
marks.

e.g.
colour == “blue”
style == “straps”
heel == “4-inch”
grade <> ‘A’

Conditions are evaluated when the instruction containing it is carried out. When
the condition is met, the condition is said to be true; if the condition is not met,
then the condition is said to be false.

When using the command IF, the instructions forming the condition and
selection are called a construct.
The IF-THEN construct

IF <condition> THEN
<one or more instructions to be carried out if the condition is true>
ENDIF

IF marks the beginning and ENDIF the end of the construct. In this construct,
the instructions between IF and ENDIF are only executed if the condition is
true.

Read the time. If the time is 11, output Ring the bell

Solution
START
PRINT ‘Enter the time’
READ time
IF time = 11 THEN
PRINT ‘Ring the bell’
ENDIF
STOP

Read a number N. If N is greater than 100, add 10 to the number. Print


the number.

Solution
START
PRINT ‘Enter a number’
READ N
IF N > 100 THEN
N = N + 10
ENDIF
PRINT N
STOP

The IF-THEN-ELSE construct

Syntax
IF <condition> THEN
< one or more instructions to be carried out if the condition is true>
ELSE
< one or more instructions to be carried out if the condition is false>
ENDIF

The IF-THEN-ELSE statement provides a secondary part of execution when the


condition evaluates to false. When the condition is true, the instructions
between IF and ELSE will be carried out. When the condition is false, the
instructions between ELSE and END if will be carried out.

Input the age of a person. If the age is greater than 35, output ‘old person’
otherwise output ‘young person’.

Solution
START
PRINT ‘Enter the age’
Read age
IF age > 35 THEN
PRINT ‘old person’
ELSE
PRINT ‘young person’
ENDIF
STOP

A student is given a 5% discount off the fees for a course if the fees are paid
before 30 days. Read a fee and the number of days. Output the fee,
discount amount, and the fee less the discount amount.
START
PRINT ‘Enter the fee and the number of days’
READ fee, days
IF days < 30 THEN
discountamt = fee * 5/100
ELSE
discountamt = 0
ENDIF
amtdue = fee – discountamt
PRINT ‘Fee’, fee
PRINT ‘Discount amount’, discountamt
PRINT ‘Fee less discount amount’, amtdue
STOP

The IF-THEN-ELSE-IF construct

START
IF <condition> THEN
<one or more instructions>
ELSE
IF <condition> THEN
<one or more instructions>
ELSE
IF <condition> THEN
<one or more instructions>
ENDIF
ENDIF
ENDIF
STOP

This variant includes the ELSE IF clause which allows for the testing of a series
of conditions in a prescribed order. When the statement list corresponding to
the first true condition is found, the instructions are executed. All other
statements that a connected to conditions are skipped.
A stadium has 4 stands, A, B, C and D. The admission fee for stand A is
$2.00, stand B is $2.50, stand C is $4.00 and stand D is $5.00. Read a stand
and the number of spectators in the stand. Calculate and print the revenue
for the stand.

Solution
START
PRINT ‘enter a stand and the number of spectators’
READ stand, spectators
IF stand = ‘A’ THEN
revenue = spectators * 2.00
ELSE
IF stand = ‘B’ THEN
revenue = spectators * 2.50
ELSE
IF stand = ‘C’ THEN
revenue = spectators * 4.00
ELSE
IF stand = ‘D’ THEN
revenue = spectators * 5.00
ENDIF
ENDIF
ENDIF
ENDIF
PRINT ‘Stand’, stand
PRINT ‘Revenue’, revenue
STOP

Making a selection based on two or more conditions


The selection to be chosen could depend on two or more conditions. When this
is required, logical operators AND, OR, and NOT are used.

Logical operators
These allow a program to make a decision based on multiple conditions. Each
operand is considered a condition that can be evaluated to a true or a false value.
The value of the conditions is used to determine the overall value of a
compound statement (placing two operands together and joining them with a
logical operator).

4+7=
C = 45 And C < X

Truth Tables
A truth table is a tabular representation of all the combinations of values for
inputs and their corresponding outputs. It is a mathematical table that shows all
possible outcomes that would occur from all possible scenarios that are
considered factual, hence the name. Truth tables are usually used for logic
problems as in Boolean algebra and electronic circuits.
The basic operations in truth tables:

Conjunction: An AND operation where both arguments must be true in order


for the statement itself to be true.
P Q P AND
Q
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
C = 25, X = 18

C >10 AND C <> X


TRUE And TRUE 

In order for promotion from a lower stream to a higher stream, you have to have
a yearly average >=85 OR promotion exam average has to be >=80

This hat is blue. (true) AND


This hat is red. (true) will produce a truth value of true.

This hat is blue. (true) AND


This hat is purple. (false) will produce a truth value of false.

This hat is pink. (false) AND


This hat is orange. (false) will produce a truth value of false.

Disjunction: An OR operation where both arguments have to be false in order


for the statement itself to be false.

P Q P OR
Q
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
This glass is full. (True) OR
This glass is empty. (True) will produce a truth value of true

This glass is full. (True) OR


This glass is full. (False) will produce a truth value of true

This glass is empty. (False) OR


This glass is full. (false) will produce a truth value of false

Negation: A NOT operation is one that is the opposite of the original value.

P NOT P
TRUE FALSE
FALSE TRUE

C = 15, X = 20

C = 45  False

NOT (C=45)

This is a football. (true)


This is NOT a football (false)

The number of rows in truth table is determined by 2n where n =


number of different statements

3 different statements will produce 23 rows = 2 * 2 * 2 = 8 rows.

4 different statements will produce 24 rows = 2 * 2 * 2 * 2 = 16 rows.

How do we know the different amount of true and false to ensure that
all possible combinations are accounted for?
 Start with the rightmost column for each statement and interchange
every true with a false for the powers of two starting from 20.

 Every time we move one place to the left, increase the power of two
by one then interchange the true and false statements accordingly.

For example. If we have 3 statements A AND B AND C, this will produce


16 columns

22 = 4 21 = 2 20 = 1
A B C A AND B AND C
TRUE TRUE TRUE
TRUE TRUE FALSE
TRUE FALS TRUE
E
TRUE FALS FALSE
E
FALSE TRUE TRUE
FALSE TRUE FALSE
FALSE FALS TRUE
E
FALSE FALS FALSE
E

Read the name of a day. If the name is ‘Monday’ or ‘Tuesday’ print


‘Correct day’

Solution
START
PRINT ‘Enter the day’
READ day
IF day = ‘Monday’ OR day = ‘Tuesday’ THEN
PRINT ‘Correct day’
ENDIF
STOP

Case statements
A case statement is a control structure that allows a selection to be made
between several sets of statements. The choice is dependent on the value of
some expression.

START
PRINT ‘Enter the student’s mark’
READ mark
Case based on mark
mark >=100
Report “Perfect Score”
mark > 89
Report “Grade = A”
mark > 79
Report “Grade = B”
mark > 69
Report “Grade = C”
mark > 59
Report “Grade = D”
Default
Report “Grade = F”
End Case
PRINT ‘The student’s grade is’, Grade
STOP

Loops (iteration)
A loop is the repeating of instructions until a condition is met. Loops are
specifically useful when you have to perform the same task multiple times.
Types of loops

1. For loop
Syntax
FOR <variable> = <beginning> TO <ending> STEP <increment> DO
<instructions which are to be repeated>
ENDFOR
FOR is the beginning and ENDFOR the ending of the loop. The variable is
used to count the number of times the loop is executed. The value of this
variable starts at the beginning value and is increased by one each time the
loop is executed, unless otherwise directed by the STEP clause.
The STEP clause indicates how much the loop variable is to be increased by
each time the loop is executed. The STEP clause is not necessary if the
increment is 1. Use the minus sign (-) with the increment value to decrease
the loop variable value.
When the end value is reached, the loop terminates and the instruction
following ENDFOR is then executed.
The beginning, ending and increment values can be constants or variables.
Variables give greater flexibility for altering the number of times the loop is
required to repeat. When variables are used, the said variables must be read
as input or stored in the computer’s memory before the instruction is
encountered.
Write an algorithm to print the numbers from 1 to 10

Solution
START
FOR count = 1 To 10 DO
PRINT count
ENDFOR
STOP

Write an algorithm to count down in twos from 10 to 0

Solution
START
FOR count = 10 TO STEP -2 DO
PRINT count
ENDFOR
STOP

Write an algorithm to calculate and print the average score for each
student in a class of 25. Each student was given three tests.

Solution
START
FOR count = 1 TO 25 DO
READ score1, score2, score3
sum = score1 + score2 + score3
average = sum/3
PRINT ‘The average is’, average
ENDFOR
STOP

Special Case – Reading N values

Sometimes, instead of telling you how many numbers to read, a problem


might say N (or some other variable) numbers. You can also get this
number from the user.

Write an algorithm that reads N ages and for hose that are more than
65, say ‘Senior citizen’

Solution
START
PRINT ‘Enter the number of ages you are going to enter’
READ N
FOR count = 1 TO N DO
PRINT ‘Enter the age’
READ age
IF age > 65 THEN
PRINT ‘Senior citizen’
ENDIF
ENDFOR
STOP

2. WHILE LOOP

A WHILE loop is used when the number of repetitions is not previously


known.

Syntax
<an initial value for the condition>
WHILE <condition> DO
<instructions which are to be repeated
ENDWHILE

The initial value for the condition can be stored in a variable which is read
or it can be a value which is assigned to a variable.

The initial value is necessary so that the comparison for the condition can be
made when the WHILE instruction is executed the first time.

The condition is made up of the said variable which stores the initial value
called the loop variable, an operator and a termination constant. The
termination constant is known as the dummy value or the sentinel value. A
dummy value is not a real value for the problem being solved. For example,
999 could be the dummy value for terminating the entry of ages of
individuals, as an age of 999 is not real. The variable chosen to form part of
the condition must match the data type of the dummy constant.
For example
WHILE A <> 999 DO (numeric constant)
WHILE A < 20 DO (numeric constant)
WHILE name <> “END” (string constant)

In a WHILE loop, the instructions between WHILE and ENDWHILE are to


be repeated as long as the condition is true. When the condition becomes
false, the repetition ceases and any instructions following the ENDWHILE
statement are then executed.

An essential requirement when using the WHILE construct is that withing


the WHILE-ENDWHILE statements, an instruction which changes the
value of the loop variable must be present. This instruction causes the loop
to be terminated. If the instruction is not present, the instructions of the loop
will be repeated forever.

Write an algorithm to calculate and print the average of three (3) scores
for a number of students terminated by 999

START
PRINT ‘Enter the three grades. Enter 999 for the first grade to stop’
READ A, B, C
WHILE A <> 999 DO
SUM = A + B + C
AVERAGE = SUM/3
PRINT ‘The average is’, AVERAGE
PRINT ‘Enter the three grades. Enter 999 for the first grade to stop’
READ A, B, C
ENDWHILE
STOP

Write the algorithm and a program that finds the average for an
unknown set of positive numbers.

Start
Sum = 0
Count = 0

Print ‘Enter a positive number. Enter a negative number to stop’


Read num
While num > 0 do
Count = count + 1
Sum = sum + num
Print ‘Enter a positive number. Enter a negative number to stop’
Endwhile
Average = sum/count
Print ‘the average is’, average
Stop

Using a while loop, write a program that accepts the name, price and
quantity of some items. Calculate the amount due for each item.
Output the name, price, quantity and amount due for each item.
Algorithm
Start
Print ‘Enter the name, price and quantity of the item, Enter END to stop’
Read name, price, quantity
While name <> ‘END’ do
Amount_due = price * quantity
Print ‘Name of item’, name
Print ‘price of item’, price
Print ‘quantity purchased’, quantity
Print ‘amount due’

Print ‘enter name, price and quantity of the item’


Read name, price, quantity
Endwhile
Stop

Write an algorithm and a program that requests the first names and
ages of some people. Output and print their names and ages.

Start
Print ‘enter the name and age’
Read name, age
While name <> STOP do
Print ‘Name of individual’, name
Print ‘Age of individual’, age
Print ‘enter the name and age’
Read name, age
Endwhile
Stop

3. Repeat until
The REPEAT UNTIL loop is a loop that executes a block of statements until
a given condition evaluates to true. The condition will be re-evaluated at the
end of each iteration of the loop, allowing code inside the loop to affect the
condition in order to terminate it.

Since the condition is evaluated at the end of each iteration, a REPEAT


UNTIL loop will always be executed at least once, even if the condition is
already true when execution arrives at the top.

Syntax
REPEAT
<instructions to be repeated>
UNTIL <condition>

Flow chart – a diagrammatic/graphical representation of sequence of steps to


solve a problem. To draw a flowchart, the following symbols are used.
Guidelines for drawing a flowchart:
 All necessary requirements should be listed out in logical order.
 Identify the various components of the problem: input, output, processing,
decisions etc. (This can be done using the IPO chart or algorithms.)
 The flowchart should be clear, neat and easy to follow. There should not be
any room for ambiguity in understanding the flowchart.
 The usual direction of the flow of a procedure or system is from left to right
or top to bottom.
 Only one flow line should come out from a process symbol.

Sequence
Write an algorithm that reads the radius of a
circle. Calculate and print the area.
START
READ r
AREA = 3.14 * r * r
PRINT AREA
END

Read the radius of a circle. Calculate and print the circumference


BEGIN
READ r
Circumference = 2 / 3.14 * r
PRINT Circumference
END

WRITE AN ALGRITHM TO FIND THE SUM OF THREE NUMBERS


START  oval
PRINT “Enter three numbers”  parallelogram
READ num1, num2, num3  parallelogram
Sum = num1 + num2 + num3  rectangle
PRINT “The sum is”, Sum  parallelogram
STOP  oval

If- then- else


Read the temperature. If the temperature is less than 320, print “Below
Freezing” otherwise print “Above Freezing”
START
READ Temperature
IF Temperature > 32
THEN
PRINT “Below
Freezing”
ELSE
PRINT “Above
Freezing”
ENDIF
STOP

Read a variable N. Say whether N is even or odd


START
READ N
Remainder = N modulo 2
IF Remainder = 0 THEN
Answer = EVEN
ELSE
Answer = ODD
ENDIF
PRINT Answer
STOP
Write a flowchart to represent the following. Read the fare and age. If the age
is less than 12, the rate is 0.0, if the age is greater than or equal to 12, but less
than 24, the fare is 0.7, the fate is 1 otherwise.

START
READ fare, age
IF age < 12 THEN
Rate = 0.0
ELSE IF age < 24 THEN
Rate = 0.70
ELSE
Rate = 1.0
ENDIF
ENDIF
PRINT fare * rate
STOP
For loop
Initialisation  count = 1
FOR count = 1 TO 10 DO 
automatically increase count by 1

Print the odd numbers from 3 to 7


i Output
2 i +1  3
4 5
6 7
8
Print the numbers from -4 to 0

While loop
Repeat Until

7. Test Algorithm for correctness


Desk check/ Dry run
Desk checking is an informal manual test that programmers can use to verify
coding and algorithm logic before a program launch. This enables them to spot
errors that might prevent a program from working as it should.

Desk checking is a similar process to proofreading; in this exercise, the


programmer runs through lines of code to identify errors and to check logic.
Typically, the programmer will print out the code and go through it in a pencil
and paper exercise. He may run a manual test on algorithms, checking that they
work correctly and contain no coding errors. This usually involves creating a
table with columns containing line numbers, variables, conditions, and inputs
and outputs, depending on the checks he is making.
Trace table
A trace table is a technique used to test algorithms or computer programs for
logic errors that might occur while the program executes.

The trace table stimulates the flow of execution. Statements are executed step
by step and the values change when an assignment statement is executed.

When designing a trace table, draw a column for each variable used in the
algorithm and draw enough rows to form the cells to store the values.

Start tracing from the top of the algorithm and write the appropriate value in the
first vacant cell for the variable which is currently being assigned a value. A
variable can store only one item of data at a given time. The current value is the
value that should be entered in the vacant cell.
If the value of the variable is to be printed, write the value on your answer sheet
as soon as the value is obtained rather than on completion of the entire table.

When printing is required within a loop, several values may have to be printed
for the same variable depending on the number of times the print instruction
was carried out. If printing is required only outside a loop, all of the values
within the loop for the variable to be printed may not have to be printed.

1 START
2 READ r
3 AREA = 3.14 * r * r
4 PRINT AREA
5 STOP

step r Area processing


1 START
2 5 r=5
3 78.75 3.14 * 5 * 5
4 PRINT 78.75
5 STOP

Complete the following trace table

C=0
READ QTY, PRICE
WHILE QTY <> 0 DO
TOTAL = QTY * PRICE
C = C + TOTAL
READ QTY, PRICE
ENDWHILE

QTY PRICE TOTAL C


0
3 5 15 15
2 3 6 21
2 2 4 25
0 0
TOT = 0
READ S
FOR P = 1 TO S DO
READ T
IF T > 5 THEN
Q=P*T
ELSE
IF T <= 5 AND T > 3 THEN
Q=P*T+2
ELSE
Q=P*4
ENDIF
ENDIF
TOT = TOT + T
ENDFOR

S P T Q TOT
0
4 1 2 4 2
2 6 12 8
3 4 14 12
4 1 16 13
5

You might also like