0% found this document useful (0 votes)
9 views44 pages

CSE 021 - Lec02 - Prob. Solving - 02.11.21

Uploaded by

akramreda120
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views44 pages

CSE 021 - Lec02 - Prob. Solving - 02.11.21

Uploaded by

akramreda120
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Introduction to Computer

Programming
CSE 021 Fall 2021

LECTURE 02: Algorithm &


Problem Solving
Dr. Basma Hassan
basma.hassan@eui.edu.eg

1
Lecture Topics
• Computational Problem Solving
• Computational Problem Solving Steps
• What is an algorithm ?
• Algorithms Building Blocks
• Pseudocode
• Flowcharts

2
Computational Problem Solving
• Computational thinking is the processes involved in
formulating problems and their solutions in a form that can
be effectively carried out by a computer.

• Computational problem is a problem that a computer might


be able to solve or a question that a computer may be able
to answer.
• problems that can be solved by the use of computations

3
Computational Problem Solving
• Computational problem solving is solving problems by the
use of computation.
• i.e. solve a problem computationally

• Two things are needed to perform computational problem


solving:
• a representation that captures all the relevant aspects of the
problem
• an algorithm that solves the problem by use of the representation

4
Man, Cabbage, Goat, Wolf Problem
• A man lives on the east side of a river. He wishes to bring a
cabbage, a goat, and a wolf to a village on the west side of the
river to sell. However, his boat is only big enough to hold
himself, and either the cabbage, goat, or wolf.

• In addition, the man cannot leave the


goat alone with the cabbage because the
goat will eat the cabbage, and he cannot
leave the wolf alone with the goat
because the wolf will eat the goat.
• How does the man solve his problem?

5
Man, Cabbage, Goat, Wolf Problem
• A simple algorithmic approach for solving this problem is simply trying all
possible combinations of items that may be rowed back and forth across the
river.
• Trying all possible solutions is referred to as a brute force approach.

• What would be an appropriate representation for this problem?


• Only the aspects of the problem that are relevant for its solution need to be
represented.
• Should we include in the representation the …
• color of the boat?
• name of the man?
• width of the river?
• The only information relevant for this problem is where each particular item is at each
step in the problem solving.

6
Man, Cabbage, Goat, Wolf Problem
• For example, we could use a sequence to indicate where each of the objects currently are,
man cabbage goat wolf boat village
[ east , west , east , west , east , west ]

• where the first item in the sequence is the location of the man, the second is the location of
the cabbage, etc.
• Since the village is always on the west side of the river, it doesn’t move, its location is fixed
and therefore does not need to be represented.
• Also, the boat is always in the same place as the man. So representing the location of both
the man and the boat is redundant information.
• The relevant, minimal representation is given below (replacing “east”/”west” with single
characters).
man cabbage goat wolf
[ E , W , E , E ]

7
Man, Cabbage, Goat, Wolf Problem
The actual problem is to determine how the man can row objects across the river, with certain
constraints on which pairs of objects cannot be left alone.

The computational problem is to find a way to convert the representation of the start state of the
problem, when all the object are on the east side of the river,
man cabbage goat wolf
[ E , E , E , E ]
to the goal state, when all objects on the west side of the river,
man cabbage goat wolf
[ W , W , W , W ]
with the constraint that certain invalid states should never be used.

Thus, in a computational problem solving approach, a solution is found within the representation
used, which must translate into a solution of the actual problem.

8
Man, Cabbage, Goat, Wolf Problem
• For example, from the start state, there are three possible moves that
can be made, only one of which results in a valid state.
man cabbage goat wolf
[ E , E , E , E ] START STATE

[ W, W, E , E ] [ W, E , W, E ] [ W, E , E , W ]
Man rows cabbage across Man rows goat across Man rows wolf across

INVALID STATE

VALID STATE INVALID STATE
Goat left alone Cabbage left Cabbage left alone
with wolf alone with wolf with goat

9
Man, Cabbage, Goat, Wolf Problem
• We check if the new problem state is the goal state. If so, then we
solved the problem in one step! (We know that cannot be so, but the
algorithmic approach that we are using does not.)
man cabbage goat wolf
[ E , E , E , E ] START STATE

[ W, E , W, E ]
Man rows goat across

Is goal state [ W, W, W, W ] ? No
Therefore we continue searching from the current state.

10
Man, Cabbage, Goat, Wolf Problem
• Since the man can only row across objects on the same side of the
river as himself, and the only object currently with him is the goat,
there are only two possible moves from here,
man cabbage goat wolf
[ W , E , W , E ] INTERMEDIATE STATE

[ E , E , W, E ] [E, E, E, E]
Man rows back alone Man rows goat across


VALID STATE
Goat left alone on west side

VALID STATE (but unproductive)
Man and all others on east side previously in this state. It
Man, Cabbage and Wolf on east side is the start state. Therefore no progress made!

11
Man, Cabbage, Goat, Wolf Problem
• This would continue until the goal state is reached,
man cabbage goat wolf
[ E , E , W , E ] CURRENT STATE

...

[ W , W , W , W ] GOAL STATE

• Thus, the computational problem of generating the goal state from the start state
translates into a solution of the actual problem since each transition between states
has a corresponding “real-world” action – of the man rowing across the river with (or
without) a particular object.

12
Computational Problem Solving
Limitations
• Once an algorithm for a given problem is developed or found, an
important question is “Can a solution to the problem be found in a
reasonable amount of time?”

“But aren’t computers very fast, and getting faster all the time?”

• Yes, but some problems require an amount of time to compute a


solution that is astronomical compared to the capabilities of current
computing devices.

• A classic problem in computer science that demonstrates this is the


Traveling Salesman problem.

13
The Traveling Salesman Problem
• A salesman needs to visit a set of cities. He wants to find the
shortest route of travel, starting and ending at any city for a
given set of cities. What route should he take?

• The algorithm for solving this problem is a


simple one. Determine the lengths of all
possible routes that can be taken, and find
the shortest one – a brute force approach.
The computational issue, therefore, is for a
given set of cities, how many possible
routes are there to consider?

14
The Traveling Salesman Problem
• If we consider a route to be a specific sequence of names of cities,
then how many permutations of that list are there?
New York, Boston, Chicago, San Francisco, Los Angeles, Atlanta
New York, Boston, Chicago, San Francisco, Atlanta, Loa Angeles
New York, Boston, Chicago, Los Angeles, San Francisco, Atlanta
etc.

• Mathematically, the number of permutations for n entities is n! (n


factorial).
• How big a number is that for various number of cities?

15
The Traveling Salesman Problem
• Below are the number of permutations (and thus the number
of routes) there are for varies numbers of cities:
• Ten Cities 10! 3,628,800 (over three million)
• Twenty Cities 20! 2,432,902,008,176,640,000
• Fifty Cities 50! over 1064

• If we assume that a computer could compute the lengths of


one million routes per second:
• for twenty cities, it would take 77,000 years
• for fifty cities, it would take longer than the age of the universe!

16
Computational Problem Solving
Steps
• Clearly understand the problem
1. Analyze Problem
• Know what constitutes a solution

• Determine what type of data is needed


2. Describe Data & • Determine how data is to be structured
Algorithm
• Find and/or design appropriate algorithm

3. Implement • Represent data within programming language


Program • Implement algorithm in programming language

• Test the program on a selected set of problem


4. Test & Debug instances
• Correct and understand the cause of any errors found

17
Problem Analysis
(Understanding the Problem)
• Once a problem is clearly understood, the fundamental computational
issues for solving it can be determined.
• Involves identifying:
• the known inputs (or given data)
• what is to be obtained via outputs (the result), and
• operations that lead us to inputs and outputs
• For some problems, there is only one solution. For others, there may
be a number (or infinite number) of solutions.
• Thus, a program may be stated as finding:
• A solution
• An approximate solution
• A best solution
• All solutions

2. Describe
1.Analyze 3.Implement 4.Test &
Data &
Problem Program Debug
Algorithm
18
Program/Solution Design
Describing the Data Needed
• When solving a computational problem, either suitable
existing algorithms may be found or new algorithms must be
developed.
• Two common ways of planning the solution to a problem are
to draw a flowchart and to write pseudocode, or possibly
both.

2. Describe
1.Analyze 3.Implement 4.Test &
Data &
Problem Program Debug
Algorithm
19
Program Implementation
• It specifies which programming language to use, or how to
implement the program.
• Translate the logic from the flowchart or pseudocode, or
some other tool, to a programming language.
• The implementation needs to be expressed in a syntactically
correct and appropriate way, using the instructions and
features available in the programming language.

2. Describe
1.Analyze 3.Implement 4.Test &
Data &
Problem Program Debug
Algorithm
20
Program Testing
• Programming errors are pervasive, persistent and inevitable.
• As a result software testing is a crucial part of software
development that is used to determine the quality of a
program and find bugs (problems).

• Testing is done incrementally …


• while program is being developed
• when the program is complete
• when the program needs to be updated.
2. Describe
1.Analyze 3.Implement 4.Test &
Data &
Problem Program Debug
Algorithm
21
Program Testing
• A test case is a set of input values and expected output of a
given program.
• A test plan consists of a number of test cases to verify that a
program meets all requirements.
• A good strategy is to include “average,” as well as
“extreme” or “special” cases in a test plan.

2. Describe
1.Analyze 3.Implement 4.Test &
Data &
Problem Program Debug
Algorithm
22
Computer Program
• Some people think of a program as being like a cooking recipe.
• A recipe consists of instructions that a chef executes, like adding eggs or
stirring ingredients.
• Example:
Baking Pancakes comes from a recipe

• Likewise, a computer program consists of instructions that a


computer executes, like multiplying numbers or outputting a
number to a screen.

23
Draw Square
• You instruct a robot to walk a certain path, via instructions like
"Turn left", "Walk forward 10 steps", or "Pen down" (to draw a line
while walking).
• Instructions:
1. Put pen down
2. Walk forward 10 steps
3. Turn left
4. Walk forward 10 steps Algorithm
5. Turn left
6. Walk forward 10 steps
7. Turn left
8. Walk forward 10 steps

24
What is an ALGORITHM?
• An algorithm is a step by step process that describes how to
solve a problem in a way that always gives a correct answer.
• When there are multiple algorithms for a particular problem, the
best algorithm is typically the one that solves it the fastest.
• As computer programmers, we are constantly using algorithms,
whether it's an existing algorithm for a common problem, like
sorting an array, or if it's a completely new algorithm unique to
our program.
• By understanding algorithms, we can make better decisions
about which existing algorithms to use and learn how to make
new algorithms that are correct and efficient.

25
Computer Algorithms
• An algorithm is a finite number of clearly described,
unambiguous “doable” steps that can be systematically
followed to produce a desired result for given input in a
finite amount of time (that is, it eventually terminates).

• The word “algorithm” is derived from


the ninth-century Arab mathematician,
Al-Khwarizmi ‫الخوارزمي‬

26
Algorithms Building Blocks
• Any algorithm is made up of three basic building blocks:

Sequencing Selection Iteration

27
Case Study:
Course Grading Problem
• If we were asked to write a program that given as input
marks of four courses of a student and should calculate the
average mark and report whether the student has passed or
failed in each course. Considering that the student must
get at least 50 marks to pass any course

28
Algorithms Building Blocks:
Sequencing
• An algorithm is a step-by-step process, and the order of
those steps are crucial to ensuring the correctness of an
algorithm.
• Here's an algorithm that calculates the average mark of four
courses (Mathematics, English, History, and Science):
1. Assume that grades summation is 0
2. Summation = Mathematics mark + English mark + History mark +
Science mark
3. Calculate the average grade as = Summation / 4
• Try following the above steps in different orders, swap step
2 & 3, and see what comes out. Not the same, is it?

29
Algorithms Building Blocks:
Selection
• Algorithms can use selection to determine a different set of
steps to execute based on a specific condition (Boolean
expression)
• Here's an algorithm that given a course mark and determine
whether the student is passed or failed in that course:
1. If the mark is greater than or equal to 50:
a. Student is passed
2. Otherwise:
a. Student is failed

30
Algorithms Building Blocks:
Iteration
• Algorithms often use repetition to execute steps a certain
number of times or until a certain condition is met.
• We can add iteration to the previous algorithm to determine
the student state in each of the four courses:
1. Store list of marks
2. For each mark in marks list of the four courses:
a. If the mark is greater than or equal to 50:
i. Student is passed
b. Otherwise:
i. Student is failed

31
Course Grading Algorithm
• By combining sequencing, selection, and iteration, we've successfully
come up with a full algorithm for Pass of Fail course grading problem.

1. Assume that grades summation is 0


2. Summation = Mathematics mark + English mark +
History mark + Science mark
3. Calculate the average grade as = Summation / 4
4. Store marks in a list
5. For each mark in the marks list of the four courses:
a. If the mark is greater than or equal to 50:
i. Student is passed
b. Otherwise:
i. Student is failed

32
Pseudocode
• Pseudocode: fake code
• An English-like informal language that has no syntax rule
• Not meant to be compiled or executed
• Used to create model program
• No need to worry about syntax errors, can focus on program’s design
• Can be translated directly into actual code in any programming language

33
Flowchart
• A flowchart is a pictorial representation of a step-by-step
solution to a problem.
 A diagram that graphically depicts the steps in a program.
• It is a map of what your program is going to do and how it is
going to do it.
• It consists of:
• symbols representing actions (i.e., input/output, process, etc.).
• arrows representing the flow of the program by connecting
symbols.

34
Flowchart Symbols
Symbol Name Function

An oval, or terminator, represents the starting and


Start / End ending points of a process

A line is a connector that shows the flow of the sequence


Arrow and direction of a process

A parallelogram represents information entering (inputs)


Input / Output or leaving the system (outputs)

A rectangle represents a process or some particular


Process operation

Decision A diamond indicates a decision or branching point.

35
Flowchart Example 1:
Area of Triangle
Start
• Step1: Read base & height
• Step2: Calculate area = (base * height)/2 Read base
& height
• Step3: Print area calculated
• Step4: Stop. area =
(base * height)/2

Print area

Stop

36
Flowchart Example 2:
Number is Positive or Negative
Start
• Step1: Read number
• Step2: If number is greater than Read
Number
or equal two zero, go to step 4
• Step3: Print “number is negative”,
Is number ≥
go to step 5 Yes 0 No
• Step4: Print “number is positive”
Print Print
• Step5: Stop. number is
positive
number is
negative

Stop

37
Flowchart Example 3:
Largest Number of 3 Numbers (Algorithm)
• Step1: Read three numbers a, b, & c
• Step2: If a is greater than b, go to step 5
• Step3: If b is greater than c, go to step 8
• Step4: Print “c is the largest”, go to step 9
• Step5: If a is greater than c, go to step 7
• Step6: Print “c is the largest”, go to step 9
• Step7: Print “a is the largest”, go to step 9
• Step8: Print “b is the largest”, go to step 9
• Step9: Stop.

38
Flowchart Example 3:
(Flowchart) Start

Read
a, b, & c

Yes No
Is a > b

Is a > c Is b > c
Yes No Yes No

Print ‘a’ is Print ‘c’ is Print ‘b’ is Print ‘c’ is


largest largest largest largest

Stop

39
Flowchart Example 4: Start

Average of N Numbers Read n

Sum = 0,
• Step1: Read (n) how many numbers to sum count = n

• Step2: Start with sum = 0, count = n n=0

• Step3: Repeat step 4, 5 and 6 till n = 0 No


Read x
• Step4: Read (x) the current number Yes

• Step5: Add value of x to sum Add x to sum


Decrement n

• Step6: Decrement the value of n (counter) Average = sum


/count
• Step7: Calculate average = sum/count
• Step8: Print average Print average

• Step9: Stop. Stop

40
Algorithm vs. Flowchart

Algorithm Flowchart
Is a finite sequence of well defined steps Is a pictorial or graphical representation of
for solving a problem a program
It is written in the natural language like
It is drawn using various symbols
English

Not easy to understand Easy to understand

Difficult to show branching and loops Easy to show branching and loops

Can be written for any problem Impractical for big problems

41
Online Test1

You have to sign in with your


official EUI email

42
Start

Online Test1 Read


number list

• According to the following Yes List has


flowchart, what will be the only one
num
output if input with a list of
No
numbers as [ 2, 5, 7 ] Print Yes
No
1st num ≤
2nd num
a. Print Yes  (Correct answer)
Yes
b. Print No Remove the 1st
num from list
c. Nothing (No output)
d. Empty List Print 'No

Stop

43
End of Lecture!
Thanks for your Attention!

44

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy