CSC1302 IPS Lecture Note
CSC1302 IPS Lecture Note
Sani
Referral materials:
We have attached two PDF textbooks with this lecture material:
1. Problem Solving & Programming Concepts by Maureen Sprankle and Jim Hubbard. (For
further reading and consultations)
2. Al-Sweigart-Automate-The-Boring-Stuff-With-Python_-Practical-Programming-For-
Total-Beginners-No-Starch-Press-2019 (Step-step guide in installing python, as well as
programming in python with exercises)
It will be in your interest to practice all exercises and attempt all questions listed in this
material.
1
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Objectives:
1. Describe the difference between heuristic and algorithmic solutions to problems.
2. List and describe the six problem-solving steps to solve a problem that has an
algorithmic solution.
3. Use the six problem-solving steps to solve a problem.
1.0 Introduction:
1.1 Problem-solving
2
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
People make decisions every day to solve problems that affect their lives. The problems may be as
unimportant as what to watch on television or as important as choosing a new profession. If a bad
decision is made, time and resources are wasted, so people must know how to make decisions well.
There are six steps to follow to ensure the best decision.
3
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
This list should be as complete as possible. You might want to talk to other people to find other
solutions than those you have identified. Alternative solutions must be acceptable ones. You could
go from Maiduguri to Abuja by way of Kano, but this would probably not be an acceptable solution
to your travel needs.
4. Select the best way to solve the problem from the list of alternative solutions
In this step, you need to identify and evaluate the pros and cons of each possible solution before
selecting the best one. To do this, you need to select criteria for the evaluation. These criteria will
serve as the guidelines for evaluating each solution.
5. List instructions that enable you to solve the problem using the selected solution
These numbered, step-by-step instructions must fall within the knowledge base set up in Step 2. No
instruction can be used unless the individual or the machine can understand it. This can be very
limiting, especially when working with computers
To evaluate or test a solution means to check its result to see if it is correct, and to see if it satisfies
the needs of the person(s) with the problem. (When a person needs a piece of furniture to sleep
on, buying her a cot may be a correct solution, but it may not be very satisfactory.) If the result
is either incorrect or unsatisfactory, then the problem solver must review the list of
instructions to see that they are correct or start the process all over again.
4
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Example 2:
5
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Example 3:
Problems do not always have straightforward solutions. Some problems, such as balancing a
checkbook or baking a cake, can be solved with a series of actions. These solutions are called
algorithmic solutions. Once the alternatives have been eliminated, for example, and once one has
chosen the best among several methods of balancing the checkbook, the solution can be reached by
completing the actions in steps. These steps are called the algorithm.
The solutions to other problems, such as how to buy the best stock or whether to expand the
company, are not so straightforward. These solutions require reasoning built on knowledge and
experience and a process of trial and error. Solutions that cannot be reached through a direct set
of steps are called heuristic solutions.
6
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
1) Heuristic Strategy
1. Draw a Diagram
Example 1:
7
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Example 2:
Solution:
8
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Example 3:
2. Make a List
Example 1:
9
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Example 2:
Solution:
Solution:
10
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
11
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
12
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
13
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Solution:
In this course, the term solution means the instructions listed during step 5 of problem-solving. The
instructions that must be followed to produce the best results. Results mean the outcome or the
completed computer-assisted answer. Program means the set of instructions that make up the
solution after they have been coded into a particular computer language.
Computers are built to deal with algorithmic solutions, which are often difficult or very time-
consuming for humans. People are better than computers at developing heuristic solutions.
Solving a complicated calculus problem or alphabetizing 10,000 names is an easy task for the
computer, but the problem of how to throw a ball or how to speak English is not. The difficulty lies
in the programming. How can problems such as how to throw a ball or speak English be solved in a
set of steps that the computer can understand?
The field of computers that deals with heuristic types of problems is called artificial intelligence.
Artificial intelligence enables a computer to do things like build its knowledge bank and speak in a
human language. As a result, the computer’s problem-solving abilities are similar to those of a human
being. Artificial intelligence is an expanding computer field, especially with the increased use of
Robotics. Until computers can be built to think like humans, people will process most heuristic
solutions and computers will process many algorithmic solutions. Therefore, this book will deal only
with algorithmic solutions.
Algorithmic problem-solving strategies, therefore, refer to systematic approaches used to solve
problems using algorithms. These strategies provide a structured framework for analyzing problems,
designing algorithms, and finding solutions. Here are some commonly employed algorithmic problem-
solving strategies:
14
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
1. Divide and Conquer: This strategy involves breaking down a complex problem into smaller,
more manageable subproblems. Each subproblem is solved independently, and the solutions are
combined to obtain the final solution. This approach is often used in algorithms like merge sort
and quicksort.
2. Greedy Method: Greedy algorithms make locally optimal choices at each step with the hope of
finding a global optimum. The strategy involves making the best decision based on the current
information without considering future consequences. The greedy approach is efficient but may
not always lead to the optimal solution. Examples include the greedy algorithms for minimum
spanning trees and the knapsack problem.
3. Dynamic Programming: Dynamic programming involves solving a problem by breaking it down
into overlapping subproblems and solving each subproblem only once. The solutions to
subproblems are stored and reused to avoid redundant computations, leading to improved
efficiency. Dynamic programming is commonly used in problems like the Fibonacci sequence,
shortest path algorithms, and sequence alignment.
4. Backtracking: Backtracking is a systematic search algorithm that explores all possible solutions
by incrementally building a solution and undoing choices when they are determined to be
incorrect. It is often used in problems that involve finding all possible configurations or
permutations, such as the N-Queens problem or solving Sudoku puzzles.
5. Branch and Bound: This strategy involves exploring the search space of a problem by branching
into different possibilities and bounding the search based on certain criteria. Branch and bound
algorithms are commonly used in optimization problems to find the best feasible solution within
a search space.
6. Linear Programming: Linear programming is a technique used to optimize a linear objective
function subject to linear equality and inequality constraints. It involves formulating the problem
as a set of linear equations or inequalities and finding the values that optimize the objective
function. Linear programming is commonly used in resource allocation, production planning, and
scheduling problems.
7. Network Flow: Network flow algorithms focus on optimizing the flow of resources through a
network of interconnected nodes and edges. Problems like the maximum flow and minimum cut
problems are solved using network flow algorithms. These algorithms are used in transportation
planning, network design, and flow network analysis.
15
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
These are just a few examples of algorithmic problem-solving strategies. Each strategy has its strengths
and applicability, and the choice of strategy depends on the nature of the problem and the desired
solution. Effective problem-solving often involves a combination of these strategies and their
adaptation to specific problem domains.
End of Unit 1.
16
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Objectives
When you have finished this section, you should be able to:
1. Differentiate between variables and constants.
2. Differentiate between character, numeric, and logical data types.
3. Identify operators, operands, and resultants.
4. Identify and use functions.
5. Identify and use operators according to their placement in the hierarchy chart.
6. Set up and evaluate expressions and equations using variables, constants, operators,
and the hierarchy of operations.
2.1 Introduction
Although problems that arise in daily life are of many types, problems that can be solved on computers
generally consist of only three:
1. Computational, problems involving some kind of mathematical processing;
2. Logical, problems involving relational or logical processing, the kinds of processing used
in decision-making on the computer; and
3. Repetitive, problems involving repeating a set of mathematical and/or logical instructions.
This section explains some computer fundamentals and demonstrates ways to set up expressions and
equations to solve these types of problems on the computer.
17
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Two of the most fundamental concepts that you will learn in this section are the constant and the
variable. A programmer takes the data, the unorganized facts, and the information, organized facts,
relevant to a problem and defines them as constants or variables. They are the building blocks of the
equations and expressions that ultimately make up solutions to computer problems. The
programmer defines each constant and variable in a problem solution as a particular data type, such
as numeric or character.
Other concepts that are essential to developing computer solutions to problems are operators and
functions. Operators are the many signs and symbols that show relationships between constants
and variables in the expressions and equations that make up the solution. The programmer has
to know all of the many operators and how to use them. The order in which operators are processed
is determined by a hierarchy that programmers need to know as well.
Operators are combined with constants and variables to create expressions and equations.
Expressions and equations are used in instructions that are the building blocks of the solution.
Functions are sets of instructions that are so commonly used that they are built into a computer
language, saving the programmer the trouble of writing them.
These are key concepts. Without an understanding of how the computer uses and defines data,
knowing what the operators are, and without knowing how to use these concepts to construct
expressions and equations, a programmer cannot effectively use the computer to solve problems.
18
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
For example, because the value of PI does not change, it would be a constant and defined within the
program.
In contrast, the value of a variable may change during processing. In many languages, variables
are called identifiers since the name identifies what the value represents. You need to be aware
of this when learning the syntax and terminology of each language. In this course, the word variable
will be used. A programmer must give a name to each variable value used in a solution. The
programmer uses a variable name as a reference name for a specific value of the variable. In
turn, the computer uses the name as a reference to help it find that value in its memory. The computer
sets up a specific memory location to hold the value of each variable name found in a program.
Variables can be any data type, just as constants can.
19
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
20
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
1. First, it allows several programmers to work on the same project without the problem of
conflicting variables and module names.
2. Second, it allows programs to be easily read because there is only one consistent name for a
variable. It also increases the readability between applications because the form of the variable
name is consistent within a company.
3. Third, naming conventions allow the code to be easily maintained.
4. Fourth, the software should perform more efficiently by using consistent naming of modules
and variables.
5. Naming conventions should produce a clean, well-written program.
6. Programmers spend most of their time on software maintenance, not development; therefore,
having a convention for naming variables decreases the time and increases the reliability when
updating software.
7. Lastly, most software is maintained by many different people. Naming conventions allow the
software to be transferred with the least difficulty.
The rules for naming variables differ from language to language. However, the general rule is to name
the variable as near to its meaning as possible: Payrate for the rate of pay, Hours for the number of
hours worked during the pay period, and the like.
It is important to understand the difference between the name of a variable and the value of a
variable.
• The name is the label the computer uses to find the correct memory location;
• The value is the contents of the location.
The computer uses the variable name to find the location; it uses the value found at the memory
location to do the processing.
It is also important to be consistent in the use of variable names because the computer will go only
to the location with the specified name, regardless of whether it is the one intended by the user. For
example, if you use Hours for hours worked, then you must use Hours at all times in referring to hours
worked, not Hrs. or Hours_Worked. If the computer cannot find a memory location by the specified
name, it will either name a new memory location and yield an incorrect result, or it will return
an error message indicating there is no location as referenced and then cease execution.
21
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
22
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
The data the computer uses are of many different types. Computers must be told the data type of
each variable or constant. The most common data types are
1. Numeric,
2. Character, and
3. Logical.
• Integers are whole numbers, such as 5,297 or -376. They can be positive or negative.
• Real numbers, or floating-point numbers, are whole numbers plus decimal parts such as
0.5674 or -0.5674.
Numeric data are used for values, such as rate of pay, salary, angles, distance, or radius, that have
calculations performed on them.
Each data type has a data set, the set of symbols necessary to specify a datum as a particular data
type. A data set is the set of values that are allowed in a particular data type. The data set for the
numeric data type includes all base 10 numbers, the plus sign (+), and the negative sign (-). The data set
for the integers includes all whole numbers within the limitations of the computer or the language, and for the real
numbers, all whole numbers with decimal parts within the limitations of the computer or the language, including zero as
a whole number and zero as a decimal part.
23
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
The character data set sometimes called an alphanumeric data set, consists of all single-digit
numbers, letters, and special characters available to the computer—a, A, Z, 3, #, &, and so forth—
placed within quotation marks. An upper-case letter is considered a different character from a lower-
case letter.
Characters cannot be used for calculations even if they consist of only numbers. When more
than one character is put together, the computer considers this item a string derived from a string of
characters. Some languages do not differentiate between characters and strings. All character data are
considered string data.
Character data or string data can be joined together with the + operator in an operation called
concatenation. When two pieces of character data are joined, the concatenation results in the second
being placed at the end of the first, as in “4” + “4” = “44” (not “8”). Concatenation could be used to
join a first name with a last name or to join pieces of data together to make a code for an inventory
item. The concatenation operator varies with each language. An example is presented below:
24
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
25
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
26
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
for each user-defined data type. If the data item is not contained within the data set, it is not part
of the set. For example, if the programmer does not include Mouse as part of the data set for a user-
defined data type of computer parts, then the computer does not recognize a Mouse as a computer
part.
27
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
28
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Data and instructions are temporarily stored in the computer’s internal memory during the
processing. When data, information, or programs have to be kept for future use, they are stored
externally on an external storage medium such as a hard disk drive in storage areas called files.
There are two types of files: program files and data files.
• Program files contain the instructions to tell the computer what to do. This book helps
the programming student create programs that will be saved on the external storage device as
program files.
• Data files contain the data required to execute the program files.
2.8 Functions
Functions are small sets of instructions that perform specific tasks and return values. They are
usually built into a computer language. Functions are used as parts of instructions in a solution.
Because they are basic tasks that are used repeatedly in the problem-solving process, by using them a
programmer or user can shorten the problem-solving time and improve the readability of the
solution. Each language has a set of functions within it. This set varies with the language and the
computer. Most languages allow programmers to write their functions. Libraries of functions
can be added to many languages.
The form of a function is the name of the function followed by an open parenthesis, followed
by the data needed to perform the function, and concluded by a closed parenthesis:
𝐹𝑢𝑛𝑐𝑡𝑖𝑜𝑛𝑁𝑎𝑚𝑒(𝑑𝑎𝑡𝑎)
Functions use data. The data is listed as part of the function and are called parameters. Functions
normally do not alter the parameters. A parameter can be a constant, a variable, or an expression.
(An expression is a calculation, such as interest/100, which has not been given a permanent memory
location in the computer.).
29
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
As a programmer, you need to investigate the functions used in the language in which you are
writing your solution. These functions have been divided into classes.
1. Mathematical functions. Often used in science and business, mathematical functions calculate
such things as square root, absolute value, or a random number. Other mathematical functions used
primarily for scientific purposes have not been included in the table.
2. String functions. These are used to manipulate string variables. For example, they copy part of
the string into another variable, find the length or the number of characters in the string, and so
forth.
3. Conversion functions. These functions are used to convert data from one data type to another.
For example, since character strings cannot be used in calculations, one of these functions would
convert a string value to a numeric value.
4. Statistical functions. These functions are used to calculate things such as maximum values,
minimum values, and so forth.
5. Utility functions. This class is very important in business programming because most reports
require some use of utility functions. They access information outside the program and the language
in the computer system. Examples of these include date and time functions.
30
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
31
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
2.9 Operators
The computer has to be told how to process data. This task is accomplished through the use of
operators. Operators are the data connectors within expressions and equations. They tell the
computer how to process the data. They also tell the computer what type of processing
(mathematical, logical, or whatever) needs to be done. The types of operators used in calculations and
problem-solving include
1. Mathematical,
2. Relational, and
3. Logical operators.
Without these operators, very little processing can be done. The operand and the resultant are two
concepts related to the operator.
• Operands are the data that the operator connects and processes.
• The resultant is the answer that results when the operation is completed.
For example, in the expression 5 + 7, the + is the operator, 5 and 7 are the operands, and 12 is the
resultant. Operands can be constants or variables. The data type of the operands and the
resultant depends on the operator.
ii. Relational operators include the following: equal to =, less than ,<, greater than >, less than or
equal to <=, greater than or equal to >=, and not equal to !=. A programmer uses relational
operators to program decisions. The operands of a relational operator can be either numeric
or character (a string); however, both operands must be of the same data type. The resultant
of a relational operation is logical data type True or False. The programmer designs one
action or set of actions that will follow when a relational expression is True, and another action or
set of actions that will follow when the expression is False. The use of relational operators is
the only way for the computer to make decisions.
Relational operators are also used to control repetitive instructions called loops. A set of
instructions to enter data for a client, which would be repeated until the data are entered for every
client, is one example of a loop. When the computer processes this type of instruction, the loop repeats
32
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
until the resultant changes from True to False, or vice versa. In the example, the results would change
when the computer can find no more client data to enter.
iii. Logical operators are the third type of operator. Logical operators are used to connect
relational expressions (decision-making expressions) and to perform operations on logical
data. For example, a store might require a driver’s license or a check-cashing card on file for a
customer to cash a check. When the customer has a driver’s license, the check can be cashed.
When she has a check-cashing card, the check can be cashed. The expression is written as License
OR Card. License and Card are the operands. They are logical data; that is, the value of each is True
or False. The operator is OR. The resultant is True or False depending on the values of the operands.
When one or both of the operands is True, then the resultant is True. When both of the operands
are False, then the resultant is False.
33
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
The OR operator is one of three logical operators. The others are AND and NOT.
When the AND operator is used, the resultant is True only when both of the operands are True. When
either or both of the operands are False, the resultant is False. A programmer uses AND when two
requirements must be True for an action or set of actions to take place.
The NOT operator is the only logical operator that requires only one operand. The resultant of the
NOT operator changes in an operand from True to False, or from False to True. A programmer uses
the NOT operator to change an operand to the opposite value. This operation is sometimes called
reversing the value of the operand.
Quick Reminder: Hope we can remember the concept of operator precedence. Sometimes called
BODMAS in mathematics. If not make sure you check that out.
This is, if you are encountered with a problem involving all three logical operators, you start with the
NOT, then AND, and lastly, the OR.
Secondly, the overall formulae for identifying the size of a truth table is 2𝑛 . Where n is the number of
variables involved.
i.e., A, B, C = 23 = 8. Therefore, there will be 8 combinations of true/1 and false/0.
1) OR
2) AND
35
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
3) NOT
We can as well have a combination of two or more of the operators. For example.
36
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
An equation stores the results of an expression in a memory location in the computer through
the equal sign. The expression above would be used as part of an instruction in the equation:
𝐴𝑟𝑒𝑎 = 𝐿𝑒𝑛𝑔𝑡ℎ ∗ 𝑊𝑖𝑑𝑡ℎ
The resultant of the expression Length * Width would then be stored in a memory location called
Area.
37
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
As you can see in Table XXX below, expressions use no equal sign (except as a relational operator)
and are used as part of an instruction, such as part of an equation. The resultant of an expression is
not stored and, therefore, is unavailable for use at another time. An expression can use numeric, string,
character, or logical data types.
For the beginning programmer, a big part of learning to solve problems on the computer is learning
how to write and evaluate expressions and equations. Remember that, to evaluate means to test
for correctness using actual data. The following examples illustrate how to use the concepts you’ve
learned in this unit to write and evaluate expressions and equations.
38
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
All variables, constants, and operators have to be on the same line. There must be an operator
between variables and/or constants. For the computer, there are no assumed multiplication signs.
Parentheses are added when the hierarchy has to be reordered or when parentheses would improve
readability.
39
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
In this simplified version, we calculate both solutions of the quadratic equation directly without using
if and else statements. We assume the quadratic equation always has two solutions, whether they are
real or complex. By defining the coefficients, a, b, and c, we calculate the discriminant using the
formula b^2 - 4ac. Then, we calculate the solutions solution_1 and solution_2 using the quadratic
formula. Finally, we print the values of the solutions to the console using print() statements.
Note that this basic implementation assumes that the quadratic equation always has two solutions and
doesn't account for the case when the discriminant is negative, which would result in complex
solutions.
Quick Homework: Try implementing several other equations using Python language in any IDE of
your choice.
Possible Sample questions
1.
2.
40
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
3.
4.
5.
6.
7.
41
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
1. If Statement: The if statement allows the execution of a block of code only if a specified condition
is true. It has the following structure:
Example
In this code, the if statement checks whether the value of x is greater than 5. If the condition is true,
the code block indented under the if statement is executed, which in this case prints the message "x is
greater than 5".
Note that the code block executed under the if statement is defined by the indentation (typically four
spaces or a tab). It's important to maintain consistent indentation for proper syntax and to indicate
which code block belongs to the if statement.
You can modify the value of x and observe how the if statement behaves based on the condition. If
x is greater than 5, the message will be printed; otherwise, nothing will be printed in this specific
example.
2. If-else statement: The if-else statement extends the if statement by providing an alternative
code block to execute when the condition is false. It has the following structure:
42
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Example
In this code, the if-else statement checks whether the value of x is greater than 5. If the condition is
true (i.e., x is greater than 5), the code block indented under the if statement is executed, which prints
the message "x is greater than 5". If the condition is false (i.e., x is not greater than 5), the code block
indented under the else statement is executed, which prints the message "x is not greater than 5".
By using an if-else statement, you can provide alternative code blocks to execute based on whether a
condition is true or false. In this example, the appropriate message will be printed depending on
whether x is greater than 5 or not.
3. If-elif-else statement: The if-elif-else statement allows for multiple condition checks and
provides different code blocks based on the first condition that evaluates to true. It has the
following structure:
43
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Example
Now let’s look at a more general example of application of the above discussed
Example: Here's an implementation of checking the days of the week using an if-elif-else statement
in Python:
Quick Homework: Implement the application of if-elif-else statements: a grading system based on a
student's score. Use any python IDE of your choosing.
44
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
These control structures provide additional ways to handle different scenarios and control the
program's flow based on specific conditions or requirements. They enhance the flexibility,
efficiency, and robustness of programs by allowing repetitive operations, handling exceptions, and
making decisions based on varying conditions.
Each programming language may have its own syntax and specific implementation of these
control structures, so it's important to refer to the documentation and guidelines of the particular
programming language you are using.
1) Loops
Loops are control structures in programming that allow the repeated execution of a block of code.
They provide a way to iterate over a sequence of elements, perform a set of instructions multiple
times, or repeatedly execute a block of code until a certain condition is met. Loops are essential
for automating repetitive tasks and implementing algorithms that require repeated actions.
45
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
i. For Loop: The for loop is used when the number of iterations is known or when iterating
over a sequence of elements. It iterates over a given range or collection and executes the
block of code for each element in the sequence. The loop continues until all the elements have
been processed.
Syntax:
ii. While Loop: The while loop is used when the number of iterations is uncertain or depends
on a specific condition. It repeatedly executes a block of code as long as the specified condition
remains true. The loop continues until the condition evaluates to false.
Syntax:
46
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Loops can be combined with other control structures, such as conditional statements (if-elif-else),
to create more complex algorithms. They allow for efficient and concise code by avoiding the
repetition of similar statements. Additionally, loops often involve the use of loop control
statements like break and continue to further control the flow within the loop.
It's important to ensure that the loop has an exit condition to prevent infinite looping. Without an
appropriate exit condition, the loop will continue indefinitely, leading to program freezing or crashing.
47
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
i. Break Statement: The break statement is used to exit the current loop prematurely. When
encountered, it terminates the loop immediately, and the control of the program moves to
the next statement after the loop.
In a for loop or while loop, if a specific condition is met and the break statement is encountered, the
loop is immediately terminated, and the program continues with the next statement after the loop.
Example using a for loop:
In this example, the loop iterates through the list of fruits. When the fruit "cherry" is encountered, the
break statement is executed, causing the loop to terminate. As a result, only "apple" and "banana" are
printed.
ii. Continue Statement: The continue statement is used to skip the rest of the current
iteration within a loop and move to the next iteration. When encountered, it jumps to
the next iteration of the loop without executing any remaining statements within the current
iteration.
Example using a for loop:
48
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
In this example, the loop iterates through the list of numbers. When an even number is encountered
(determined by the condition num % 2 == 0), the continue statement is executed, skipping the
remaining statements in that iteration. As a result, only the odd numbers are printed.
Break and continue statements provide flexibility within loops to control the flow of execution. They
can be used to optimize code, skip unnecessary iterations, or terminate a loop prematurely based on
specific conditions. By utilizing these statements, you can have finer control over the behavior of your
loops and tailor them to meet the requirements of your algorithm.
49
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Linear data structures are data structures in which individual data elements are stored and
accessed linearly in the computer memory. Examples lists, stacks, queues, and arrays
A non-linear data structure, as the name implies, is a data structure in which the data items are
not stored linearly in the computer memory, but data items can be processed using some
techniques or rules. Typical non-linear data structures are Trees.
In this course we focus only on introductory linear data structures i.e., arrays and list.
1. Arrays
In computer programming, an array is a data structure that stores a collection of values of the same
data type. Each value in an array is called an element, and each element is accessed by its index or
position within the array.
Arrays can be declared and initialized with a specific number of elements, or their size can be
dynamically allocated at runtime based on the program's needs. The elements of an array can be
of any data type, including integers, floating-point numbers, characters, and even other arrays.
Arrays are a part of the array module and are designed to store elements of the same data type. The
type of elements in an array is specified during its creation.
50
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
2. List
A list data structure is a collection of elements that are ordered and can be accessed by their position,
typically starting from zero. Lists can contain elements of any data type, such as numbers, strings,
or objects, and can be resized dynamically during runtime. In most programming languages, lists
are implemented as arrays with additional methods and properties that make them easier to use.
Elements of a list can be of different data types. This is called a heterogeneous list. In many
programming languages, including Python and JavaScript, lists are dynamic and can store elements of
any data type. This means that you can store integers, floats, strings, Booleans, and even other lists or
objects in a single list. For example, in Python, you can create a list with elements of different data
types like this:
51
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Objectives
Introduction
Computers are only as good as their hardware, their software, and the people using them. Assuming
the hardware has been engineered to accomplish a given job, the efficiency of the computer relies
on the effectiveness of the programmer.
The computer must be told what to do. It needs a set of instructions, the solution, in order to
process data in the correct sequence and reach the desired results. For greatest efficiency, the
programmer or the user has to be able to easily read and interpret the solution. The solution will be
most effective if the programmer follows certain steps and rules that have been developed over the
years. The solution becomes a program when it is coded into a computer language during the
final stages of programming.
The type of problem the computer can solve best is one that can be solved algorithmically that is,
the problem can be solved with a single sequence of instructions. These instructions must be
written in a way the computer can understand, and the computer executes them in the order
presented in the program. If the instructions are written according to the appropriate rules and they
correctly follow the syntax of the computer language, then the computer will complete the task.
Although this scrupulous adherence to the instructions is usually what the programmer wants, it is
also, believe it or not, the most frustrating thing about the computer. If the instructions make sense
to the computer, it will complete them. If the programmer has made an error in the instructions,
the results are not likely to be what was intended (GIGO). The computer does not reason, nor
does it read minds; it only follows instructions (AI is changing the narrative now).
52
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
53
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Algorithms are composed of well-defined instructions or steps that are executable and can be followed
by a computing device or a human. Each step specifies an action to be performed, such as arithmetic
calculations, comparisons, conditionals, loops, or function calls.
Algorithms must terminate after a finite number of steps. They should not run indefinitely or enter
infinite loops. The algorithm's termination ensures that a solution or output is eventually obtained.
An algorithm is considered correct if it produces the expected output for all valid inputs.
Ensuring correctness involves rigorous testing, validation, and verification techniques.
Algorithms aim to achieve efficiency in terms of time and space requirements. Time complexity
refers to the amount of time an algorithm takes to run, often measured in terms of the number of
operations. Space complexity refers to the amount of memory or resources an algorithm consumes.
Now here is the python implementation with and without the use of a function
1. With function
54
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
2. Without function
Quick Homework:
1. FUK CAR Parking System.
This system allows only cars with a FUK sticker to park at designated car park known as PARK 1.
Stickers are categorized into senior stickers and junior stickers and are parked at marked spots labelled
as S and J respectively. Cars without stickers would be registered at the gate and be sent to a different
car park know as PARK 2. Develop an algorithm using both of its representations to show the
procedure to solving the problem. Afterward, implement in python using an IDE of your choice.
55
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
• A flowchart shows the flow of the processing from the beginning to the end of a solution.
• Each block in a flowchart represents one instruction from an algorithm.
• Flowlines indicate the direction of the data flow.
• Most blocks have one or more entrances, flowlines directing the flow of the data into the
block.
• Most blocks have only one exit, flowlines directing the data out of the block, since, in most
cases, data can flow to only one other block
There are flowchart symbols for use with various types of processing. Figure XXX below shows and
explains some general flowchart symbols. There are many specific symbols, such as printer output,
monitor output, and so forth, that are used in systems flowcharts.
56
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
57
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
Quick Homework:
1. FUK CAR Parking System.
58
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
From the algorithm developed, draw the corresponding flowchart utilizing all necessary symbols
discussed.
3.2.3 Pseudocode
Pseudocode is similar to the algorithm without the numbers and somewhat condensed.
Pseudocode is a high-level, informal, and human-readable description of a computer program or
algorithm. It is not a specific programming language but rather a way to express the logic and structure
of code using plain language and simple constructs. Pseudocode helps in planning, designing, and
understanding algorithms before implementing them in a particular programming language.
While pseudocode lacks strict syntax rules, it often uses common programming constructs like
variables, loops, conditionals, and function calls to represent algorithmic steps. It focuses on
expressing the logic and flow of an algorithm in a clear and concise manner.
In this pseudocode:
• The program starts with the "Start" statement.
• The "Read" statements prompt the user to input the values of num1 and num2.
• The "Set" statement calculates the sum of num1 and num2 and assigns it to the variable sum.
• The "Display" statement shows the value of sum as the output.
• Finally, the program ends with the "End" statement.
Note that this pseudocode focuses on expressing the logical steps of the algorithm in a human-
readable manner. It doesn't include specific syntax or language rules since pseudocode is not
59
Introduction to Problem Solving (CSC 1302) | Course lecturers: Mr. J. Isuwa & Mal. K. Sani
tied to a particular programming language. It serves as a blueprint for implementing the addition
algorithm in any programming language later on.
60