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

Problem Solving and Programming Content Handout

The document provides an overview of key programming concepts such as variables, data types, algorithms, pseudocode, and flowcharts. It defines variables as named locations that store values in memory. Constants are similar but do not change value. Common data types include integers, floating point numbers, characters, and strings. The document then defines algorithms as precise sequences of steps to solve problems, and notes they should have a header, declaration, body, and terminator. Pseudocode is described as a way to represent algorithms using mathematical notation and English statements. Flowcharts are introduced as a graphical way to represent algorithms using shapes like rectangles, diamonds, and arrows. Two short examples of a pseudocode algorithm and flowchart are also provided.

Uploaded by

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

Problem Solving and Programming Content Handout

The document provides an overview of key programming concepts such as variables, data types, algorithms, pseudocode, and flowcharts. It defines variables as named locations that store values in memory. Constants are similar but do not change value. Common data types include integers, floating point numbers, characters, and strings. The document then defines algorithms as precise sequences of steps to solve problems, and notes they should have a header, declaration, body, and terminator. Pseudocode is described as a way to represent algorithms using mathematical notation and English statements. Flowcharts are introduced as a graphical way to represent algorithms using shapes like rectangles, diamonds, and arrows. Two short examples of a pseudocode algorithm and flowchart are also provided.

Uploaded by

Shavane Davis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Information Technology

PROBLEM SOLVING AND PROGRAMMING – Content Handout

The following are extracts from Observer Lecture series.

PROGRAM DESIGN
After defining the problem, based on the steps of the problem solving phase you find a solution to the
problem. In finding a solution to the problem, you have to also analyze alternative solutions to the problems.
When we are solving problems on the computer this is done by representing the most efficient solution as an
algorithm. Before we look at the term algorithm, there are some key terms you must first be familiar with
and there are variables, constant and data types.

When you ask the computer to read two numbers, find the sum of the two numbers then output the sum.
When the computer reads the two values it has to store the values somewhere in memory. Similarly, it will
have to store the value of sum somewhere in order to provide an output to you the user. These values are
normally stored in what we call variables.

 A variable is a named location in memory that stores a particular value. This value may be changed
during the execution of a program. Examples of variable names include: ‘number’, ‘age’, ‘name’,
‘length’ and so on. You can have several different names, numbers, ages etc.

 A constant provides locations for storing data which do not change value during execution of a
program. For example if you were calculating the perimeter of a circumference, you will need to
include PI which is normally 3.17 in your calculation. In the formula PI would remain constant.

 Data Types: Variables typically store values of a given type. There are several data types but we
will be focusing primarily on the following data types: Integers, Floating point (real), characters and
strings.
o Integers – Used to store whole numbers
o Floating point/Real – Used to store real or fractional numbers
o Characters – Any single character in the ASCII set (a single character such as a letter of the
alphabet or punctuation)
o String – a collection of characters such as a word, phrase or sentence

1
KEY PROGRAMMING TERMS

 Algorithm – A sequence of steps designed to perform a particular task. Algorithm can be


written in any suitable form such as in a programming language or pseudo-code.

 Pseudo code – An imitation computer program written using mathematical notations and
English-like statements to describe the logic to solve a problem or carry out a procedure.

 Test Data – Data which is used to test a program for errors/special data created by a
programmer to test the correctness of the program.

 Dry-Run – The process whereby a program is checked to ensure that it does what it was
designed for.

 Bug – A software bug may be defined as a coding error that causes an unexpected defect,
fault, flaw or imperfection in a computer program.

 Structured Walkthrough – A manual trace of the logics of a program using test data.

 Run-Time Errors – Run time errors occurs when a syntactically correct program statement
cannot execute successfully. A common example is attempting to divide by zero (0).

 Loading – The process of transferring program and data from secondary storage to primary
storage.

 Syntax errors –These are errors reported by the compiler/interpreter when the rules of the
language is not obeyed.

 Logical errors – These errors occur when the expected results of a program are not met.

 Testing – This is the process of checking a program for errors.

 Debugging – This is the process of testing, locating and correcting mistakes by running the
program.

We have come to the end of lesson twenty six in our series of lessons in the CSEC Information Technology
lectures. See you next week where we will begin to look at The Pascal Language. Remember if you fail to
prepare, you prepare to fail.
Here’s a diagram illustrating the relationship between the source code and the object code.

SOURCE TRANSLATOR OBJECT


CODE CODE

COMPILER or2
INTERPETER
ALGORITHMS

An algorithm is a sequence of precise instructions for solving a problem in a finite amount of time.

The properties of an algorithm are:

 It must be precise (exact)


 It must be unambiguous (in other words it must be clear)
 It must give the correct solution in all cases
 An algorithm must terminate or eventually end

Algorithmic Structure

Every algorithm should have the following sections, in the stated order:

Header: Algorithm’s name or title


Declaration: A brief description of the algorithm and variables used. That is, a statement of the purpose as
well as initialization of the variables.
Body: Sequence of steps
Terminator: An end statement

The Algorithmic Language

When writing algorithms the language gradually progresses from English towards a notation that resembles
that of a programming language. An intermediate notation called pseudo-code is commonly used to express
algorithms. A pseudo-code is an imitation computer program written using mathematical notations and
English-like statements to describe the logics to solve a problem or carry out a procedure. The pseudo-code
is used as a guide to code the solution to the problem in a high level language.

Parts of a pseudo-code algorithm

A pseudo-code algorithm contains one or more of the following statements:

 Input Statements
 Assignment Statements
 Output Statements
 Control Statements (Sequence, Selection, Repetition)

We are going to be examining each of these statements in our next lesson.

3
DO’s AND DON’Ts WHEN WRITING PSEUDOCODE

You should do the following:

 Use the assignment symbol ( ) in assignment statements instead of the equal sign.
 Use meaningful variable names
 Use indentation to show the logic and scope of control structures
 Insert comments to clarify meaning of blocks of code
You should not do the following:

 Use language-specific constructs such as case, switch statements or for loops in the pseudo-code.
Constructs such as while, repeat and if-then-else are sufficiently general and can therefore be used in
the pseudo-code. Keywords such as readln, writeln, printf, scanf should not be used.

 Attempt to write Pascal code before writing the algorithm. That is, do not execute the program first
and then try to write the algorithm afterwards, based on the program code. This is a very bad practice
and is essentially a waste of time.

We have come to the end of lesson eighteen in our series of lessons in the CSEC Information Technology
lectures. See you next week where will continue to look at algorithms. Remember if you fail to prepare, you
prepare to fail.
Example 1

Write a pseudocode algorithm to read the values of three numbers find the product of the numbers and output
the product.

Algorithm Product {The algorithm header}

This algorithm finds the product of three numbers {The Declaration}

Input statement
Start
Read num1, num2, num3 Assignment statement
{The Body of the
Product num1 * num2 * num3 Algorithm}

Print Product Output statement

Stop {The Terminator}

4
FLOWCHARTS
A flow chart is a graphical representation of an algorithm. They use special geometrical objects to designate
the basic steps of a program, which are:

1. A parallelogram
This is used to represent the input operation as well as the output operation

2. A rectangle
This is used to represent a processing /assignment statement.

3. A diamond
This is used to represent a decision (if-then-else and loops) structure.

4. An elliptical shape
This is used to represent the terminal indicators, START or STOP

5. Directional Arrows
These are used to indicate the flow of the logic in the algorithm.

6.

The connector
We have come to the end of lesson nineteen in our series of lessons in the CSEC Information Technology
lectures. See you next week where will continue to look at pseudocode and flowcharts. Remember if you
fail to prepare, you prepare to fail.

5
Example 1

Write a pseudocode algorithm to read the values of three numbers find the product of the numbers and output
the product.

Algorithm Product {The algorithm header}

This algorithm finds the product of three numbers {The Declaration}

Input statement
Start
Read num1, num2, num3 Assignment statement
{The Body of the
Product num1 * num2 * num3 Algorithm}

Print Product Output statement

Stop {The Terminator}

THE PASCAL LANGUAGE

PSEUDOCODE KEYWORDS PASCAL KEYWORDS

1) The word Start is used to begin an algorithm The word Begin is used to start a Pascal program

2) The word Read is used to input values The words Read and Readln is used to input values

3)Multiplication * and Division / Same

4) Assignment Symbol = or Assignment symbol :=

5) To display results/messages: Print, Display, To display results: Write or Writeln


Output

6) To end an algorithm the word Stop is used To end a Pascal program the word End followed by
a full stop is used. (End.)

6
KEY DISTINCTIONS IN PASCAL

 The difference between READ and READLN


There is no difference between read and readln when working with numeric values such as 2, 6, and 10. The
difference applies when working with string values or characters on different lines such as ‘A’, ‘B’ and ‘C’.
When the computer reads the first letter (‘A’) if you use the keyword READ the program will not move to
the next line to read B and C. So the keyword READLN is used to read in such values.

 The difference between WRITE and WRITELN


The keyword Write outputs text or values to the screen in a single line leaving the cursor positioned at the
end of line. On the other hand Writeln which means write line, outputs text or values to the screen in more
than one line leaving the cursor at the beginning of the next line, instead of at the end of the current line.
For example, if you were outputting the sentence “My First Program”.

Using the Write keyword it would look like this:-

My first program. __ The Cursor is


positioned at the
end of the line.

Using the keyword Writeln it would appear on the screen like this:-

My The words are displayed on


first separate lines and cursor is
program. positioned at the beginning
__ of the next line.

Example 1

Write an algorithm to read three numbers and find the average of the numbers and output the average of the
numbers.

Pseudocode Version

Algorithm Average

This algorithm finds the average of three numbers.

Start
Read num1, num2, num3
Average (num1 + num2 + num3)/3
Print “The average is”, Average
Stop

7
Program
Pascal Code Heading
Comments shown in
Program Average_of_Numbers (input,output); parenthesis.
{This algorithm finds the average of three numbers}
var num1, num2, num3: integer; Declaring your variables
Begin and their data type
Readln(num1, num2, num3);
Average := (num1 + num2 + num3)/3; Program Block
Writeln(‘The average is:’, Average);
End.
Program
Terminator
Please Note:
 All program statements and lines are terminated with a semi-colon (;), except the ‘begin’ and ‘end’
keywords. Program statements preceding an end statement do not require a semi-colon (optional).
 When outputting text to the screen as oppose to pseudocode where double quotations are used, in
Pascal single quotations are used. For example: Writeln(‘I Love to Program’);

We have come to the end of lesson twenty seven in our series of lessons in the CSEC Information
Technology lectures. See you next week where we will continue to look at The Pascal Code. Remember if
you fail to prepare, you prepare to fail.

RELATIONAL OPERATORS & TRUTH TABLES


Table 2 shows a truth table with examples for each of the relational operators. As the table shows, A is set to
20 and B is set to 15. When we check equally with the equal operator, both sides must be equal or same for
the expression to be true. Because the 20 is not equal to 15, the A = B is false. In this case, the expression is
true because 20 is greater than 15. Using similar logic, the table shows results for other relational operators.

Table 2 truth table for relational operators


Example
Operators
(Assume A = 20, True when False when Result
Symbol
B = 15)
A and B are A and B are
= A=B False
same or equal different
A is greater than A is not greater
> A>B True
B than B
A is not less than
< A<B A is less than B False
B
A is greater than B is greater than
>= A >= B True
or equal to B A
A is less than or
<= A <= B B is less than A False
equal to B
A is not equal to A and B are
<> A <> B True
B same or equal
8
TRUTH TABLES

A truth table is a good way to show the function of a logic gate. Logic gates process signals which represent
true or false. Normally the positive supply voltage +Vs represents true and 0V represents false. A truth
table therefore shows the output states for every possible combination of input states. The symbols 0 (false)
and 1 (true) are usually used in truth tables.
There are three main logic gates we will concentrate on for the CSEC level and they are: AND gate, OR gate
and the NOT gate. For every Logic gate we are going to be examining its corresponding truth table.
AND GATE
For the ‘AND gate’ the output Q is true if input A AND input B are both true: Q = A AND B
An AND gate can have two or more inputs, its output is true if all inputs are true.

Input A Input B Output Q


0 0 0
0 1 0
1 0 0
1 1 1
Traditional symbol
Truth Table
Remember (0) zero
represents false and (1)
one represents true

OR gate
For the ‘OR gate’ the output Q is true if input A OR input B is true (or both of them are true):
Q = A OR B
An OR gate can have two or more inputs, its output is true if at least one input is true.

Traditional symbol

Input A Input B Output Q


0 0 0
0 1 1
1 0 1
1 1 1

Truth Table

9
NOT gate (inverter)
The output Q is true when the input A is NOT true, the output is the inverse of the input: Q = NOT A
A NOT gate can only have one input. A NOT gate is also called an inverter.

Input A Output Q

0 1

1 0

Truth Table
Traditional symbol

TRACE TABLES
As indicated in the previous lesson your trace table is used to test and verify your algorithm. Let us look at
an example of how a trace table is executed using question 1 of the practice question you were given in the
previous lesson.

Example 1

Write a pseudocode algorithm to read a set of positive integers (terminated by 0) and print their average as
well as the largest of the set.

1. Numcount 0
Sum 0
Largest 0
Read Number
While Number not equal to 0 do
Sum Sum + Number
Numcount Numcount + 1
If Number > Largest
Largest Number
Endif
Read Number
Endwhile
Average Sum/Numcount
Print Average, Largest

10
The Trace Table
Example 1
We will use the following numbers as input for the trace table: 2, 5, 6, 1, 10 and 0.
Variables used for
Step 2: column headings
While number is not equal to Number Numcount Sum Largest
0, Read input value (Number)
0 0 0
Step 1:
Initializing key
Step 4:
2 1 = (0 +1) 2 = (0 + 2) 2 variables
Numcount
Numcount + 1

Step 5:
5 2 = (1 + 1) 7 = (2 + 5) 5  Compare Largest
Step 3: with Number.
Sum Sum + Number  Number is greater
6 3= (2 +1) 13 = (7 + 6) 6 than Largest, Largest
is now equal to
Number.
1 4 = (3 +1) 14 = (13+1) 6

10 5 = (4 +1) 24 = (14 + 10) 10


Note Largest remains the
same because Number
When the user enters this 0 which is ‘1’ is not larger
value the algorithm will stop than Largest which is
as this value terminates the currently 6.
program

Average Sum/Numcount Average 24/5


Average 4.8
Largest Number Largest 10

 For the example above you will first initialize your variables as shown in the algorithm.
 Then you would repeat step 2 to step 5 until the user enters ‘0’. The program will then stop.
 The average will be calculated (24/5), average is 4.8
 Both the Average and the Largest value will be printed which is 4.8 and 10 respectively.

NB: When you are repeating step 2 to step 5 until the condition is met (the program ends) you must
work with the current values stored in the respective variables.

11
Pascal Code written Using Turbo Pascal 1.5

Program Average_of_Numbers; You will observe that the format is the same
uses wincrt; with the exception of this line, which is used in
Turbo Pascal for windows. It indicates that the
var num1, num2, num3: integer; program will be able to carry out operations
Begin including input and output.

Readln(num1, num2, num3);


Average := (num1 + num2 + num3)/3;
Writeln(‘The average is:’, Average);
End.

We are now going to look at how to code an if statement, for loop and while loop using Turbo Pascal 1.5, but
before we begin there is two key things I need to point out when coding in Pascal.

1. Naming Variables
A variable must begin with a letter, and then followed by any digit, letter or the underscore character. No
character space is allowed when naming your variables. For example, you can have variables like: num1,
A1, Product_Calculation and so on rather than variables like: 6Num, _Grade and Average Calculation.

2. Formatting Real Values


Pascal allows for real numbers to be formatted to a specified number of decimal places. Let say you were
adding a set of real numbers and then you were required to find the average of the real numbers and print
the average. Your program would look like this:

Program CalculatingRealNumbers;
Uses wincrt;
var num1, num2, Sum, Average: real;
Begin
Sum:= num1 + num2; 2 decimal places
Average:= Sum/2;
Write(‘The Average is’,Average:4:2)
End.
Lets say num1 = 9 and num2 = 4 and as such the average would be 2.25. Without specifying the character
spacing and decimal places the output wouldspaces
4 character look like this:-

The Average is 2.25000000000E+00

On the other hand the statement: - Write (‘The Average is’,Average:4:2) would look like this on the
screen.

The Average is 2.25 12


IF STATEMENT

You were already introduced to the If statement when we looked at conditional statements used in
Pseudocode. Just to remind you, an If statement is used to test a particular condition(s) where if the
condition is true a statement is executed else if it is false another statement is executed.

An Example of an If statement in Pascal is shown below:

Example 1

Write a program to read a number, find the square of the number and print the square of the number if is
greater than 100 else output THE SQUARE IS TOO SMALL.

Program Square_of_Numbers;
Uses wincrt;
Var num, Square:integer;
begin Note that there is no semi colon
Read(num); placed at the end such that the
else statement can be executed
Square:= num * num if the condition is not true.
if Square > 100 then
Writeln(Square)
else
Writeln(‘THE SQUARE IS TOO SMALL’)
end.

FOR LOOPS

Remember your ‘For Loops’ are definite loops, whatever is placed in the blocked of the loop will be
executed a specified number of times. Let’s look at an example of a ‘For Loop’ using Pascal code.

Example 2

Write a program to read 10 integer scores, find the sum of the 10 scores and output the sum.

Program Sum_of_Scores;
Uses wincrt;
Var NoOfScores, score, sum:integer;

13
Begin
Sum:= 0; Initialization
of variables The
NoOfScores:= 0 Repetitive
For NoOfScores:= 1 to 10 do Statement
Begin
Block Statements that will be
writeln(‘Enter next score’); repeated 10 times enclosed in
readln(score); another begin and end, except
this ‘end’ ends with a semi
sum:= sum + score; colon.
End;
writeln(‘The Sum is: ‘, Sum);
End.

WHILE LOOPS

While loops on the other hand are indefinite loops, the block statements will continue to be executed until a
particular condition is met.

Example 3

Write a program to read a set of marks terminated by 999, the program should also find the sum of the marks
and also output the sum of the marks.

Program SumOfMarks;
Uses wincrt;
Var Mark, Sum:integer;
Begin
Sum:= 0; { Initialization of variable}
Writeln(‘Enter A Mark’); The Repetitive Statement,
Readln(Mark); with a terminating value
to stop the program
While Mark < > 999 do
begin
Sum:= Sum + Mark; Block Statements that will be
Writeln(‘Enter A Mark’); repeated until the user enters
999 enclosed in another begin
Readln(Mark);
and end
end;
Writeln(‘The Sum is:’,Sum);
End.
14
We have come to the end of lesson twenty eight in our series of lessons in the CSEC Information
Technology lectures. See you next week where we will continue to look at The Pascal Code and Arrays.
Remember if you fail to prepare, you prepare to fail.
ARRAYS

Loading elements (values) into an Array


Using the keyboard (allowing the user to enter the value)
Program Test_Scores2;
Uses wincrt;
Var Scores: Array[1..3] of integer;
Begin Allowing input of the values
Read(Scores[1]); directly from the keyboard by the
Read(Scores[2]); read statement.

Read(Scores[3]);
End.

Using a For Loop with keyboard input


Program Test_Scores3;
Uses wincrt;
Var Scores: Array[1..3] of integer;
counter: integer; The Subscript or index used to
reference the values being entered from
Begin
the user into the array.
For counter:= 1 to 3 do
Begin
Readln(Scores[counter]);
End; The name of
End. the array

Remember, once you accept values from the user by means of a ‘for loop’ when you want to output the
values you use a ‘for loop’ comprising of the same array name, counter and size as shown below.
For counter := 1 to 3 do
Begin
Writeln(Scores[counter];
End;

15
To Find the Total of a set of values in an array Linear Search of an Array
list
Program SearchingArrays;
Uses wincrt;
Program Sum_Scores;
var ScoresSearch: Array [0..4] of integer;
Uses wincrt; counter, SearchValue:integer;
Found:Boolean;
Var Scores: Array[1..4] of integer; Here the values
counter, Sum: integer; Begin are requested
Begin For counter:= 0 to 4 do from the user
For counter:= 1 to 4 do Adding the and stored in
Begin values to Begin the array
Readln(Scores[counter]); sum. writeln('Enter your scores');
readln(ScoresSearch[counter]);
Sum:= Sum + Scores[counter];
End; End;
writeln( 'The Sum of the integers is ', Sum);
End. Writeln('Enter your target value');
Readln(SearchValue);

Found := false; Here the user is asked to


counter:= 0; enter a value that the
program will search for in
the array.

Repeat
if SearchValue = ScoresSearch[counter] then
Found := True;
counter:= counter + 1;
The Repeat Until loop will
Until (Found = true) OR (Counter >4);
search the array for the value
and return a statement to
if found = true then
indicate if it is found or not.
writeln('Value Found')

else writeln('Value Not Found');

End.

16
Using an array to accept and output char values

Program FirstName;
Uses wincrt;

Var Fname: Array[1..4] of String; { The data type of the elements in the array is declared as
string}
counter: integer;
Begin
For counter:= 1 to 4 do
Begin Prompting the user to
writeln('Enter the letters of your first name and press enter'); enter his/her first
Readln(Fname[counter]); name then storing it.
End;
write('My First name is: ');
For counter := 1 to 4 do Displaying the User’s
Begin first name
write(Fname[counter]);
End;
End.

The output on the screen would look something like this:


My First name is: Mary

17

You might also like