CSC1302 - Lectuer Notes
CSC1302 - Lectuer Notes
COURSE TUTOR:
BASHIR ABDU MUZAKKARI, Ph.D.
This document does not claim any originality and cannot be used as
substitute for prescribed textbooks. The information presented here is
purely a collection by the course lecturer for teaching assignments.
Various textbooks as well as freely available materials from the internet
were consulted for preparing this document. The ownership of the
information lies with the respective authors or institutions.
Introduction to Problem Solving
Computers are used for solving various day-to-day problems and thus
problem solving is an essential skill that a computer science student should
know.
2. Developing an Algorithm
3. Coding
2. Developing an Algorithm
It is essential to device a solution before writing a program
code for a given problem. The solution is represented in
natural language and is called an algorithm.
3. Coding
After finalizing the algorithm, we need to convert the
algorithm into the format which can be understood by the
computer to generate the desired solution.
More than one algorithm can be written for a particular problem, but the
choice of selecting a particular algorithm above others depends on the
following factors: reliability, accuracy, ease of modification, and execution
time when converted to a high-level language.
Components of Algorithm
Most of the algorithms used in solving program related problems consist of
three major sections: the input, processing and output.
To execute a task the algorithm requires some data (i.e. input), it performs
some computation on the data (i.e. processing) then it produces result (i.e.
output). The processing comprises of either, computation, selection,
iteration, etc. or all of them.
Characteristics of a Good Algorithm
Precision — the steps are precisely stated or defined.
Uniqueness — results of each step are uniquely defined and only depend
on the input and the result of the preceding steps.
Given different tasks, one algorithm can be applied in performing all the
tasks. This enhances the consistency and reliability of the problem solving
process.
Example of an Algorithm
Example:
Write an algorithm in natural language to calculate the area of a triangle (area
=1/2 * base * height)
Step 1: Start
Step 2: Select from the triangle the values for base and height
Step 3: Calculate the product of the values (i.e. base and height)
Step 4: Divide the product of base and height by 2
Step 5: The area is the result gotten after dividing base and height by 2
Step 6: Stop
CHAPTER 4: Representation of Algorithm
Representation of Algorithm
Algorithms are written in natural language like English and other languages.
This method is found to be too wordy and confusing.
Pseudocode
Flowchart
Pseudocode
A pseudocode (pronounced Soo-doh-kohd) is another way of representing
an algorithm. It is considered as a non-formal language that helps
programmers to write algorithm.
Step 1: Start
Step 2: Read base and height
Step 3: Product = base x height
Step 4: Area = product/2
Step 5: Print Area
Step 6: Stop
Benefits of Pseudocode
Before writing codes in a high level language, a pseudocode of a program
helps in representing the basic functionality of the intended program.
Each shape represents a step of the solution process and the arrow
represents the order or link among the steps.
Start
Print Area
Stop
General Rules of Flowcharting
All boxed of the flowchart are connected with arrows not lines.
All flowchart symbols have an entry point on top of the symbol with no
other entry points. The exit point for all flowchart symbols is on the bottom
except for the Decision symbol.
The Decision symbol has two exit points; these can be on the side or the
bottom and one side.
Exercises1:
Write an algorithm to find the square of a number. Display the pictorial
representation of the algorithm using a flowchart.
Exercise 2:
Draw a flowchart to solve the problem of a non-functioning light bulb.
Exercise 3:
Write an algorithm to check whether a number is odd or even. Present
your algorithm in Psuedocode and flowchart
Algorithm
Exercises
Exercises4:
write a pseudocode and draw a flowchart where multiple conditions are
checked to categorize a person as either child (<13), teenager (>=13 but
<20) or adult (>=20),based on age specified.
Exercise 5:
Write pseudocode and draw a flowchart to accept 5 numbers and find their
average
Exercise 6:
Write pseudocode and draw flowchart to accept numbers till the user
enters 0 and then find their average.
CHAPTER 5: Verifying Algorithms
Verifying Algorithm
Why is verification of algorithm an important step in problem solving?
For example, if we are told that the formula for the sum of first N natural
number is N(N+1)/2, how do we verify it?
The method of taking an input and running through the steps of the
algorithm is sometimes called dry test or dry run.
C++ gives programmers a high level of control over system resources and
memory.
C++ Syntax
int main() {
cout << "Hello World!";
return 0;
}
The cout object, together with the <<
operator, is used to output
#include <iostream>
values/print text: using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning
C++";
return 0;
}
Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords),
for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
string - stores text, such as "Hello World". String values are surrounded by double quotes
bool - stores values with two states: true or false
Variables
To create a variable, you must specify the data type and assign it a value.
type variable = value;
Where type is one of C++ types (such as int), and variable is the name of the
variable (such as x or myName). The equal sign is used to assign values to the
variable.
They can repeat actions or start new actions based on new information.
Example
1. unlock the door
2. open the door
3. enter the room
4. switch on the light
5. close the door behind you
Flow of Control
Selection Flow
Double Alternative
Multiple Alternative
Flow of Control
Selection Flow
Single Alternative
if (condition) {
// statement goes here
}
Example
if (20 > 18) {
cout<< "20 is greater than 18";
}
Flow of Control
Selection Flow Example
int time = 20;
Double Alternative if (time < 18) {
if (condition) { cout<< "Good day.";
// statement if true } else {
} else { cout<< "Good evening.";
// statement if false }
} // Outputs "Good evening."
Flow of Control
Selection Flow Example
int time = 22;
Multiple Alternative if (time < 10) {
if (condition1) { cout<< "Good morning.";
// condition1 is true } else if (time < 20) {
} else if (condition2) { cout<< "Good day.";
//condition1 is false & } else {
condition2 is true cout<< "Good evening.";
} else { }
condition1 and condition2 // Outputs "Good evening."
are both false
}
Flow of Control
Selection Flow
Multiple Alternative
The algorithm about entering the room could be changed to
account for different conditions. For instance, it could change
to:
1. IF the door is locked, THEN unlock the door, ELSE do nothing
(go to next instruction)
2. IF the door is closed, THEN open the door, ELSE do nothing
3. Enter the room`
4. IF the room is dark, THEN switch on the light, ELSE do nothing
5. Close the door behind you.
Flow of Control
Selection Flow
Multiple Alternative
The sequence of actions that is carried out is selected based upon the
information.
The only way for a computer to discover the circumstances is to collect inputs
and compare them to known values.
In this case, known values would be values such as 'locked' or 'unlocked',
'closed' or 'open'.
The computer looks at the door and checks to see if its current state matches
'closed' and 'locked'. If it matches 'locked', the door needs to be unlocked.
Otherwise, nothing should be done.
Flow of Control
Selection Flow
Multiple Alternative
The selection IF-THEN-ELSE is useful if the choices are binary, e.g.
True or False.
Basically, IF-THEN-ELSE looks for the correct option from two choices
where CASE looks at the correct option from multiple choices.
Flow of Control
Selection Flow switch(expression) {
case x:
Switch Case // code block
break;
The switch case statement is used case y:
when we have multiple options and // code block
we need to perform a different task break;
for each option. default:
// code block
}
Flow of Control
Selection Flow
Switch Case
Flow of Control
Iteration Flow
Count-controlled loop
Example
Condition-controlled loops
Summary
An algorithm is defined as a step-by-step procedure designed to perform an operation
which will lead to the desired result, if followed correctly.
Algorithms have a definite beginning and a definite end, and a finite number of steps.
A good algorithm, which is precise, unique and finite, receives input and produces an
output.
In order to write effective algorithms we need to identify the input, the process to be
followed and the desired output.
A flowchart is a type of diagram that represents the algorithm graphically using boxes of
various kinds, in an order connected by arrows.
An algorithm where all the steps are executed one after the other is said to execute in
sequence.
Decision making involves selection of one of the alternatives based on outcome of a
condition.
An algorithm may have a certain set of steps, which are repeating for a finite number of
times, such an algorithm is said to be iterative.
There can be more than one approach to solve a problem and hence we can have more
than one algorithm for a particular problem.
The choice of algorithm should be made on the basis of time and space complexity.
Exercises
1. Write pseudocode that reads two numbers and divide one by another and display the quotient.
2. Write the pseudocode to print all multiples of 5 between 10 and 25 (including both 10 and 25).
4. Write an algorithm to find the greatest among two different numbers entered by the user.
5. Write an algorithm that performs the following: Ask a user to enter a number. If the number is
between 5 and 15, write the word GREEN. If the number is between 15 and 25, write the word BLUE. if
the number is between 25 and 35, write the word ORANGE. If it is any other number, write that ALL
COLOURS ARE BEAUTIFUL.
6. Write an algorithm that accepts four numbers as input and find the largest and smallest of them.