Professional Documents
Culture Documents
Module 2a - Intro Problem Solving
Module 2a - Intro Problem Solving
INTRODUCTION TO PROGRAMMING
These components are then placed into a “Defining Diagram” . This is a table with three columns
which represents input output and processing used in problem solving
Activity
Problem 1
Read three numbers, calculate and print their total
Problem 2
The cost of a new car is the sum of the wholesale cost, the local sales tax and the dealer’s mark
up. Assuming the dealers mark up is 10% of the wholesale cost and the sales tax is 6%. Design
a program to read the car id and the whole sale cost of the car and print the car id and the final
cost of the car.
Problem 3
Given three integers representing the age of three boys, write a program to find and display their
average age as well as the age of the oldest boy.
Problem 4
An architect’s fee is calculated as a % of the cost of a building. The fee is made up as follows:
8% of the first $5000 of the cost and 3% on the remainder. The architect has hired you to design
a program that will accept the cost of a building and calculate and display the architect’s fee.
Problem 5
Design an algorithm that accepts two values, the hourly rate and the number of hours worked by
an employee. If the number of hours exceeds 40, then the excess hours should be paid at an
overtime rate of twice the hourly rate. Calculate the wages including overtime if any for an
employee.
Solution: Problem 1
Defining Diagram
INPUT PROCESS OUTPUT
Three number Get three numbers Total
Add numbers
Finding a solution to the problem is the “how” of solving the problem. The first thing to do in
finding a solution is to do the problem at hand and take notes of each step as you go along. It is
required that you use sample input data i.e. actual numbers/figures to be used with the problem.
Having found a solution to the problem, the programmer should not stop there. He/she should
explore alternative solutions to arrive at the most efficient solution. Here are some points to
consider when developing an algorithm solution:
Characteristics of an algorithm
a. It must be precise/exact
b. It must be unambiguous/clear
c. It must be finite i.e. it must have an end
d. It must be in a logical sequence i.e. it should pass the flow of control from one process to
another.
Variables
A variable is a symbolic name assigned to a memory location that stores a particular value that
changes during execution.
Example: We get three (3) numbers we could call them, num1, num2, num3
num1 2
Variables num2 7
num3 4
Constant
This is a symbolic name assigned to a memory location that
stores a particular value that will never change during In programming, a literal value is
program execution. For example average=sum/n written exactly as it is meant to be
interpreted. In contrast, a variable is a
Where n is three and will always be three unless the name that can represent different
amount of numbers to be averaged is changed. values during the execution of the
program and a constant is a name that
represents the same value throughout a
Literal
program. But a literal is not a name -- it
In an algorithm, a literal is a notation for representing a fixed
value in the algorithm, pseudocode, or source code. is the value itself.
NUMBER LITERALS are simply written using numerals (and a decimal point and minus sign for real number
and negative numbers respectively).
A STRING LITERAL is always placed in quotation marks. The quotation marks allow the computer to
distinguish a literal string (text) from variables and program code.
START
welcome_message “Hello class, this is my programme”
cost_of_ticket 10.5
PRINT welcome_message
PRINT “Please enter the number of students”
GET num_students
totalCost num_students * cost_of_ticket
PRINT “Cost for the entire class: $ ”
PRINT totalCost
STOP
DATA TYPES
A data type in a programming language is a set of data with values having predefined characteristics. The
data type of a value (or variable) is an attribute that tells what kind of data that value can have and what
operations can be performed on the data. Examples of data types are: integer, floating point unit number
(simply called a real number), character, string, and Boolean.
Numeric data can take mathematical operations (addition, subtraction etc) and comparison operations
(greater than, less than etc).
String data do not support mathematical operations. Strings can be concatenated (join), separated (split),
compared, the case can be changed and a few other operations.
Tips
Boolean data can only be inverted or compared.
Gender is not Boolean.
Telephone number is not a
number.
OPERATORS
Please read through the notes on operators at this point. (What is here is merely a summary)
VARIABLE DECLARATION
A variable declaration is an instruction to the computer to prepare a memory location. It has 3 essential
components and must come before the variable is used.
Examples
Often times we omit the variable declaration in writing pseudo code but this must be done when writing
PASCAL.
VARIABLE INITIALIZATION
Initialization is the first instance in which a variable is assigned a value. It is normal to initialize numbers
to 0 (zero) (real numbers to 0.0) and strings to the ‘’ (empty string).
Examples
Age 0
Num1 0.0
Name ‘’
Representing an Algorithm
1. Pseudocode
2. Flowchart
Pseudocode
This is an imitation program written using mathematical notations and English-like statements to
describe the logics to solve a problem or carry out a procedure
Flowchart
This is a pictorial representation of an algorithm. It uses different geometric shapes to show each
step in the solution to a problem.
Used to show the flow from one step (symbol) to the next
Developing Algorithms
An algorithm contains one or more of the following statements
a. Input statement
b. Assignment statements
c. Output statement
d. Control statements/structures
INPUT STATEMENT
This is used to get data from outside the computer via some input device into a variable for
manipulation.
ASSIGNMENT STATEMENT
This is used to give initial value to variables, and change the value assigned to a variable. The
assignment has two parts, the left value and the right value.
The left value refers to the variable as the storage location An expression is a statement which is
where the right value refers to what will be stored. The evaluated to produce a value.
right value refers to a value, which maybe the result of an
expression or the content of another variable. An expression is a combination of one or more literal
values, constants, variables, operators, and functions
Example that the computer interprets and computes to produce
Variablename (left value) expression (right value) (to return) another value. This process, as with
Days 28 mathematical expressions, is called evaluation.
Rate 500
Salary days * rate
OUTPUT STATEMENT
The output statement is used to get information to the programmer or the computer user. Output
can be in the form of sound, text, voice and graphics. For our purpose output will be in the form
of text or values.
Example
Print “literal statement”, variable_name
Print “Your age is”, age
During the execution of a program, the computer executes each statement in order and takes the
actions that have been prescribed by the programmer. The control structures used in programs
are:
1. Sequencing
2. Selection/Decision/Branching
3. Iteration/Repetition/Looping
Sequencing
Instructions are executed one after the other in order they are given, this is called sequence.
Each instruction will be executed in the order that it appears.
ACTIVITIES
1. Write a pseudocode algorithm to read two numbers and find their sum
2. Write a pseudocode algorithm to calculate the salary of a day’s worker. Input to the
pseudocode are the hours worked for the day and the hourly rate.
3. Write a pseudocode algorithm to read three numbers and find and display their product,
sum and average.
4. Write a pseudocode algorithm to calculate and display the cost of a product given the
quantity and the unit price.
Selection
We know that you are able to set and retrieve variables inside your program; however for a program to be really
useful it has to be able to make decisions based on the values of those variables.
The selection control structure is the presentation of a condition and the choice between two (or sometimes more)
actions. The choice made depends on whether the condition is true or false.
Note that in this example there is no ELSE action. If you want to execute instructions when the condition is false,
these actions can be contained in an ELSE clause of the IF statement as shown below.
Block: compound
statements. That is, one
or more statements
treated as a unit.
Repetition
Repetition is also known as Iteration or Looping. A loop is the presentation of a set of instructions to be performed
repeatedly (zero or more times) as long as a condition is true.
TYPES OF LOOPS
Loops are described as definite or indefinite depending on how it is controlled; and post-tested or pre-tested
depending on when the condition is checked before (pre) or after (post) the block (loop body) is done.
FOR LOOPS
The for loop behaves like a while loop (it is a pre-test loop) but with syntax specialized for creating a counter-
controlled loop (the body of the loop is typically executed a specific number of times).
The initialize clause (an assignment statement) executes only once and is typically used to set the initial
value of the counter variable.
The termination clause tests the counter variable to see if it has reached its final value.
This test occurs before the statements in the body of the loop are executed (making it a pre-test loop).
The update clause typically increments the counter and is executed immediately after the statements in the
body of the loop.
This for loop is a shortened for writing It can be written as a while loop as
FOR counter 1 TO 10 DO FOR counter 1 WHILE counter <= 10 counter 1
PRINT counter PRINT counter WHILE counter <= 10
END FOR counter counter + 1 PRINT counter
END FOR counter counter + 1
END WHILE
The variable, counter, indicates the number of times the statements in the body of the loop has already been
executed. It starts at one. The execution of this looping structure proceeds as indicated in the table below (reading
right to left and top to bottom).
WHILE LOOPS
The while loop is a pre-test loop; the condition is tested before the statements While there are more items on my
in the body of the loop are executed. While the test condition is true, execute shopping list Purchase next item and
the statements in the body of the loop. The loop terminates when the cross it off my list.
condition evaluate to false. Because the test precedes the body of the loop,
the statements in the body will never be executed if the condition is false the WHILE items on list DO
Purchase next item
very first time it is tested.
Cross off purchased item
END WHILE
Do next thing in my day
In the while loop, the program goes back and retests the condition after the
block (body) has been executed and will do the body again if the condition is still true.
Activity
Controlling a Loop
In order to function correctly, loops need to be controlled.
1. Initialize the loop control variable - i.e. declaring the variable and setting its starting value.
2. Test the loop condition - should the loop actions be executed?
3. Update the loop control variable if the loop runs - generally this involves incrementing the variable by 1,
but can be done differently.
START
INITIALISE i = 0 // 1 - initialise the loop control variable
WHILE i < n // 2 - test the loop condition
Run loop actions
Add 1 to loop control variable // 3 - update the loop control variable
ENDWHILE
END
START
INITIALISE i = 0 // 1 - initialise the loop control variable
REPEAT
Run loop actions
Add 1 to loop control variable // 3 - update the loop control variable
UNTIL i > n // 2 - test the loop condition
END
When constructing a solution to a programming question that contains a loop, ask yourself the
following questions:
The sequence control structure simply lists the lines of pseudocode. The concern is not with the sequence category
but with selection and two of the iteration control structures. The following are commonly used ending phrase-
words:
In summary, use:
A for loop for counter-controlled repetition - i.e. when the loop needs to run a certain number of times.
A while loop when it is possible that the loop may never execute.
A repeat loop when the loop must execute at least one time.
DECREMENT- to gradually decrease a numeric value, most often but not always by 1. E.g. counter counter - 1
COUNTER
When one needs to count how many times a program executes a loop (without using a counted loop), one uses a
counter. Counters need two things in order to function: 1) an Initial Value, and; 2) an Incremental Value. The initial
value is usually (but not always) zero, and must be located outside the loop. It tells the program what number to
begin counting at. The incremental value, on the other hand, tells the program what to count by (usually 1, but it
could be any number) and must be located inside the loop.
ACCUMULATOR
The most elementary use for an accumulator is adding a sequence of numbers. The numerical value in the
accumulator increases as each number is added.
START
var answer: string
var gasbill, totalbill: real
var billnumber:int
Initialize the accumulator
totalbill 0
Initialize
accumulatorthe counter
billnumber 1
repeat counter
PRINT "Enter the value of gas bill number ", billnumber, "."
PRINT "Type 0 to exit program."
READ gasbill
if gasbill = 0 then
EXIT
end if
totalbill totalbill + gasbill accumulator
billnumber billnumber + 1 counter (increment)
PRINT "Do you want to exit (Y/N)"
READ answer
UNTIL answer = "Y"
billnumber billnumber - 1 decrement
PRINT "You had ", billnumber, "gas bills."
PRINT "they totalled ", totalbill, "dollars."
STOP
Activity
Problem
Notice that
QUESTIONS
1. Write a pseudocode algorithm to read 100 numbers and find their sum.
2. Write a pseudocode algorithm to read a sequence of numbers terminated by 999. The
pseudocode should count and print the number of the negative values and zero values.
The algorithm should also print the sum of the positive numbers.
3. Write a pseudocode algorithm to read the name and test scores for ten students. Each
student does three tests. The pseudocode must print the name of the student with the
highest average. The data will be read in the following form:
Appendix
http://dsearls.org/courses/C121CompSci/Overview/ControlStructures/ControlStructures.htm
IF THEN ELSE
FOR LOOP
WHILE vs REPEAT
CONNECTORS
References
https://ritterit-programming.wikispaces.com/05.+Control+Structures
http://dsearls.org/courses/C121CompSci/Overview/ControlStructures/ControlStructures.htm
http://whatis.techtarget.com/definition/accumulator
Additional Reading
http://www.bbc.co.uk/education/guides/zrxncdm/revision/3
http://www.bbc.co.uk/education/guides/zrxncdm/revision/6