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

CSC102Lecture4_2024

The lecture covers problem solving and algorithms, emphasizing the importance of defining problems and developing structured approaches to find solutions. It introduces George Polya's strategies for problem-solving, including understanding the problem, devising a plan, executing the plan, and reviewing the outcome. Additionally, it explains the concept of algorithms, their elements, and how they can be represented through pseudocode and flowcharts.

Uploaded by

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

CSC102Lecture4_2024

The lecture covers problem solving and algorithms, emphasizing the importance of defining problems and developing structured approaches to find solutions. It introduces George Polya's strategies for problem-solving, including understanding the problem, devising a plan, executing the plan, and reviewing the outcome. Additionally, it explains the concept of algorithms, their elements, and how they can be represented through pseudocode and flowcharts.

Uploaded by

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

CSC 102

LECTURE 4

Sakpere A.B.
Department of Computer Science,
University of Ibadan.
Today’s Lecture:
Problem Solving and Algorithm...
Outline
• Problem

• Problem Solving

• How to solve problems

• Algorithms

• Pseudocode
Brainstorm Session
• What do you understand by the word
“problem”?

• Can you share an experience of any problem


you have encountered?
o Were you able to solve it?
o How did you solve it?

• Is there always a solution to every problem?


Problem…
• Some dictionary meanings:
o a question raised for inquiry, consideration or solution
o an intricate unsettled question or a source of perplexity,
distress or vexation
o a perceived gap between the existing state and a desired state
o a puzzle that requires logical thought or mathematics to solve
it.
Things to Note
• The concept of problem in this class does not
connote “a negative thing”
• Think of it as
o a puzzle
o a task to be solved
o an activity to be carried out
o a challenge to be attempted
Problem Definition
• Is it a trivial thing to discuss the concept of
“defining a problem”?

• Albert Einstein once said, “If I were given one


hour to save the planet, I would spend 59
minutes defining the problem and one minute
resolving it.”
Class Discussion

•What does Albert Einstein


mean?

•Do you support his ideology?


Problem Solving
• Solving is defined as finding a solution for
something such as a problem.
• Therefore, problem solving is the act of
finding a solution to a perplexing, distressing,
vexing, or unsettled question.
Can the computer be used to solve
all problems?
• The truth is (a) computer(s):
o can do nothing without being told what to.
o is not intelligent on its own. It relies on solutions
provided by humans.
o like everyone else, they have their limitations
o frees people from repetitive, voluminous and boring
tasks
How to solve problems
• George Polya’s book on “How to Solve It” gives
a general approach to solving problems.

• He is a mathematician and remained Stanford


Professor Emeritus for the rest of his life.
Strategies suggested by Polya
• Understanding the problem
• Devising a plan
• Carrying out the plan
• Looking back
Understanding the problem
• First you have to understand the problem
o What is the unknown?
o What are the data?
o What the condition?
o Is it possible to satisfy the condition? or insufficient?
or redundant? or contradictory?
o Draw a figure.
o Introduce suitable notation.
o Separate the various parts of the condition
o The output from the first phase is a clearly written
problem statement.
Devising a plan
• Never reinvent the wheel
o Have you seen it before? Or have you seen the same
problem in a slightly different form?
o Is there a problem related to yours that has been
solved before? Could you use the solution? Could you
use its result?
• Apply Divide and Conquer
o Break up a large task into smaller units that you can
handle. E.g. the task of cleaning the house or
apartment may seem overwhelming. Breaking into
sub-tasks such as cleaning the living room, the dining
room, the kitchen, the bedrooms, and the bathroom
seems more manageable and easier to solve.
Carrying out the plan & Looking
Back
• Carrying out the plan
o Carrying out the plan of the solution
o Can you clearly see that the step is correct?
o Can you prove that it is correct?

• Examine the result obatained


o Can you check the result?
o Can you check the argument?
o Can you derive the result differently?
o Can you see it at a glance?
o Can you use the result or method for other problem?
Applying these strategies
Scenario/Situation: Saturday is a colleague’s birthday. We are
all invited!!!
• Step 1: Understand the problem (situation)
o Who are those interested in going? How do we get there: walk, take a
taxi? What gift do we get him?
• Step 2 : Devise a plan/Divide Task
o Birthday Gift
o Set up a poll/form for those interested
o Book a Cab
• Step 3: Carry out the plan
o Birthday Gift: Purchase based on agreement in step 2
o Book a cab: Keep checking the map from time to time for instructions
• Step 4: Look back
o Compare the final point on your map to the address written on the IV
Computer Problem Solving
• Analysis and Specification Phase
o Understand/Define the problem
o Specify the problem that the program is to solve
• Algorithm Development Phase
o Develop a logical sequence of steps to be used to solve the problem
o Follow the steps
• Implementation Phase
o Translate the algorithm into code
o Test the code
• Maintenence Phase
o Use the programs and modify it to meet changing
requirements
Computer Problem Solving
Algorithm
• From Polya’s list we are expected to have a
plan. That plan is algorithm.
• Algorithm is a set of unambiguous
instructions for solving a problem or sub
problem in a finite amount of time using a
finite amount of data.
Is this an algorithm?

Tidy your
room:
Pick up all the stuff
on your floor and
put it away.
Make your bed.
Vacuum the floor.
An algorithm for Snakes and Ladders
Snakes and Ladders:
• This game is for 2 - 4 players.
• The first player to hit the last square wins and the game
ends.
• To start, each player takes his/her turn to roll the dice
and the one with the highest throw begins.
• Players then take turns to roll the die. They each move
the number of squares indicated by the die.
• If a player lands on a square depicting the bottom of the
ladder, she moves up to the square containing the top of
the ladder.
• If a player lands on the square containing the head of a
snake, he slides down to the square containing the tail of
the snake.
Is this an algorithm?
To find the sum of three numbers, a, b, c:
d=a+b+c
Ponder…
• If humans need an algorithm for virtually
every task, can a computer require less or do
without it?

• So, a program is an algorithm (or set of


algorithms) written in a particular language
to be understood by a particular class of
“computers” (people or machines or…)
Points to note on Algorithms (1)
• Algorithms must be precise so that they:
o Are repeatable
o Have a predictable outcome
o Can be executed by different “computers” (people or
machines)
o Terminate!
• The same algorithm can be represented in
different ways
AND
• Several algorithms for solving the same
problem may exist - with different properties
Points to note on Algorithms (2)
• Each step of the algorithm must be
unambiguous and have a specified action

• The range of inputs must be specified


carefully

• It must be finite
• It must generate one or more output after
processing
Elements of Algorithm
Elements of Algorithm
• Sequence
o Each step is followed by another step
• Selection
o A choice may be made among alternatives
• Iteration
o A set of steps may be repeated

• Any language with these 3 constructs can


express/implement any classical algorithm.
Control Structures
• In order to tackle a problem, we need
o a correct algorithm
o to apply the algorithm at the 'good' moment
o to decide which algorithm to apply (sometimes there are more
than one, depending on conditions)
o to know if a certain operation must be repeated
In short: we need a suitable Control Structure
• In 1966, two researchers, C. Bohn and G.
Jacopini, demonstrated that any algorithm
can be described using sequence, selection
and repetition constructs.
Sequence Construct
• Single steps or actions
in the program logic
• Statements executed Initialize A
in the order of appear- Variables

ance, with control


passing
unconditionally from
one statement to the Carry out B
next. Computation
o The program executes
Statement A followed
by Statement B.
Sequence Construct
• An example from Scratch
Example on Sequence
• Write an algorithm that will calculate the area
of a rectangle
o Step 1: Enter the length of the rectangle
o Step 2: Enter the breadth of the rectangle
o Step 3: Multiply length by breadth to get the area
o Step 4: Output the area of the rectangle
Selection Construct
• A decision point in a procedure in which the
outcome of a stated condition determines
which of two actions will be taken.

• Tests a condition and executes one of the


two alternative instruction sets based on the
results of the test.
Selection Structure
• It describes a condition we want to test

• if A>B is true (if A is greater than B) we take the


action on left
o print the value of A
• if A>B is false (if A is not greater than B) we
take the action on right Y N
o print the value of B is
A>B

Print Print
A B
Selection Structure
• Let's see an example from Scratch
Selection Structure
• Let's see an example from Scratch
Example on Selection

• Write an algorithm to calculate the average of


a student’s score in four courses. Then
indicate if the student passes or not.

o Step 1: Enter the 4 scores


o Step 2: Add the 4 scores and divide by 4
o Step 3: If (average < 45), student failed
o Step 4: Otherwise, student passed
Iteration Construct
• The logic pattern in programming in which certain
actions are repeated whenever a specified
condition occurs.

• The cycle repeats until such time as the specified


condition no longer occurs

©
Cop
yrig
ht
2000
Example of Iteration
An Example from Scratch
Example of Iteration
1. Fill kettle with water
2. Plug Kettle
3. While water has not boiled,
Wait 60 seconds
4. Turn kettle off
5. Remove plug from power outlet
Algorithm to Boil Water in Kettle
(Comprehensive)
1. take the lid off kettle
2. If there is enough water in the kettle , go to step 7
3. Put kettle under tap
4. Open tap
5. While kettle is not full,
 Wait
6. Close tap
7. Replace lid on kettle
8. Plug kettle into power outlet
9. Turn kettle on
10. While water has not boiled,
 Wait 5 seconds
11. Turn kettle off
12. Remove plug from power outlet
Algorithm to Boil Water in Kettle
1. take the lid off kettle
2. If there is enough water in the
kettle , go to step 7
3. Put kettle under tap
4. Open tap
5. While kettle is not full,
 Wait
6. Close tap
7. Replace lid on kettle
8. Plug kettle into power outlet
9. Turn kettle on
10. While water has not boiled,
 Wait 5 seconds
11. Turn kettle off
12. Remove plug from power outlet
Will this algorithm work for this kettle? Why or why not?
Representing Algorithms
• Algorithm can be technically expressed as:
o Pseudocode
o Flowchart
Pseudocode
• Pseudocode is an informal high-level
description
• Uses same structure as programming
language
• Usually written before programming and
intended for humans
Vocabulary used in Pseudocode
Input/output
• Read – reads a value into a variable. Usually used to
prompt user for a value
• Display – outputs a variable or constant usually to a
terminal

• Variable is a placeholder
Initialization & Computation
A simple Example
• Write an algorithm that will calculate the area
of a rectangle
o Step 1: Enter the length of the rectangle
o Step 2: Enter the breadth of the rectangle
o Step 3: Multiply length by breadth to get the area
o Step 4: Output the area of the rectangle

READ Length, Breadth


COMPUTE Area AS Length * Breadth
DISPLAY Area
Selection Control Statements
• if statements
§ Performs an action, if a condition is true; skips
it, if false.
e.g. if score is greater than or equal to 45,
print passed

IF (score >= 45) THEN


DISPLAY “Passed”
ENDIF
Selection Control Statements
• if … else statements:
o Performs an action if a condition is true and performs
a different action if the condition is false.
e.g.: if grade is greater than or equal to 45
print passed
else (less than 45)
print failed
IF (score >= 45) THEN
DISPLAY “Passed”
ELSE
DISPLAY “Failed”
ENDIF
Selection Control Statements
• Switch Statements/if ladder
• Performs one of several actions, based on the value
of an expression.
• Multiple-selection statement—selects among many
different actions (or groups of actions).
IF (score >= 70) THEN
DISPLAY “Grade Point is 4”
ELSE IF (score >= 60) THEN
DISPLAY “Grade Point is 3”
ELSE IF (score >= 50) THEN
DISPLAY “Grade Point is 2”
ELSE IF (score >= 45) THEN
DISPLAY “Grade Point is 1”
ELSE
DISPLAY “Grade Point is 0”
ENDIF
Iteration Control Statement
• While Statement

Example: Print +ve integers less than or equal to 5


Iteration Control Statement
• for statement
o Initialization: Starting Point
o Condition: Executes if true
o Increment: increase or decrease counter
Example
• Ex 1: Write a pseudocode to add any two
number
• Algorithm:
o Input 1st Number
o Input 2nd Number
o Add Number 1 and Number 2. Output the result.
READ number1, number2
COMPUTE sum AS number1 + number2
DISPLAY sum
Example
• Ex. 2: Calculate salary based on hours worked and
hourly rate.
• Algorithm:
o Input hours worked, rate per hour
o If hours any is less than 0, error message
o Otherwise salary = hours worked * rate/hr
Example
• Ex. 3: Determine if an integer is even or odd
Algorithm:
Input number
If number divided by 2 has no remainder, it
is even
Otherwise it is odd
Exercise
• Write an algorithm & pseudocode to convert
kilogram to gram.

• Write an algorithm & pseudocode to


determine the greater of 2 numbers

• Write an algorithm & pseudocode to print out


all the even numbers between 1 & 10
Nested Statements
• Nested for statement
Nested Statements
• Nested for if statement
Extra Assignment (Not to be
submitted)

• Write an algorithm for the following tasks:


o Write an algorithm for cooking your favorite food.
o Finding a telephone number on the Internet

• Write an algorithm, pseudocode and draw a


flowchart for finding the maximum of a list of
numbers
Reference
• Rutgers University Lecture Notes
• University of Cape Town Lecture Notes…
• General Online Resources/Pictures

You might also like