Lec 5 - Problem Solving I DR El Shimaa

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Introduction to Computers

Lecture 5 : Problem Solving

Dr. Alshaimaa Abo-alian


Information systems department, FCIS,
Ain Shams University
a_alian@cis.asu.edu.eg
Course objectives

Understanding the • Categories of Computer systems


• Components of computer systems:
terminology and • Hardware [input, processing, storage,
concepts of the output, and communications devices]
• Software [Systems as well as applications
IT domain SW])
• Data representation

• Problem solving: pseudocode and


Introduction flowcharts.

to • Introduction to programming languages


• Main elements in programming with C++:

programming Mathematical expressions, I/O statements,


Loops, Logical expressions and Branching

-2-
Grading and Assessment

Assessment Marks
Final Written Exam 50
Midterm 15
Lab Quizzes 15
Attendance & Activities 5
Practical Exam 15

Lecture participation will help your grade!


-3-
Study Materials

 Lecture Slides/Notes.
 Lab Slides

 Text Book:
 Problem Solving with C++ (9th
Edition). Walter Savitch, Pearson.
 Download PDF

-4-
Contact Information

 Office Hours:
 Monday: 10 am – 11 am
 Tuesday: 9 am – 10 am

 Thursday: 10 am – 11 am

 E-mail: a_alian@cis.asu.edu.eg

-5-
Lecture 5
Problem Solving
Problem Solving

 A problem can be defined as a difference between a


desired situation and current situation.

 A problem solution is a procedure, or method, for


transforming the current situation to the desired one.

 In computer science, an algorithm states the steps


leading to the solution, which must be transmitted to
the computer.

-7-
What is an algorithm?

-8-
Designing Algorithms

➢ There are two methods for describing algorithms:


1. Flowchart: Graphical representation that uses
standardized symbols to visually describe an algorithm
2. Pseudocode: English-like informal statements that
precisely describe the steps of an algorithm

-9-
Designing Algorithms (Cont.)

Flowchart Pseudocode

BEGIN
INPUT Number1, Number2
Sum = Number1 + Number2
PRINT Sum
END

-10-
Flowchart

 A flowchart provides a visual representation of


the steps the algorithm follows in order to show
the logic of program.
 It is a diagram made up of boxes, diamonds and
other shapes, connected by arrows.
 Each shape represents a step in the process,
while the arrows show the order in which they
occur.

-11-
Flowchart Symbols

-12-
Flowchart: General Rules

1. Every flowchart has two terminals (a START


symbol and a STOP symbol).
2. All boxes of the flowchart are connected with
Arrows (not lines).
3. Flowchart symbols have an entry point on the top
of the symbol with no other entry points.
4. The exit point for all flowchart symbols is on the
bottom except for the decision symbol.
5. The decision symbol has two exit points; these can
be on the sides or the bottom and one side.
-13-
Flowchart: General Rules cont.

6. A flowchart flows from top to bottom. However, an


upward flow can be shown as long as it does not exceed 3
symbols.
7. Connectors are used to connect breaks in the
flowchart. Examples are:
* From one page to another page.
* From the bottom of the page to top of the same page.
* An upward flow of more than 3 symbols.
8. Subroutines (predefined processes) have their own
and independent flowcharts.

-14-
5

Problem Solving Example

 How many stamps do you use when mailing a letter?


 The rule is to use one stamp for every five sheets of
paper or fraction thereof.

-15-
6

Algorithm

1. Request the number of sheets of paper; call it


Sheets. (input)
2. Divide Sheets by 5. (processing)
3. Round the quotient up to the next highest whole
number; call it Stamps. (processing)
4. Display the number Stamps. (output)

-16-
7

Flowchart Example

-17-
Pseudo-code

 Pseudo-code is a text-based approach to write


down an algorithm. Words describe the actions that
the algorithm will take.

 Keywords:
 Input: Read/Get/Accept

 Initialize: Set/Init

 Processing: Compute/Calculate/Set/Increment

 Output: Print/Display/Show

-18-
Pseudo-code Writing Rules

 Only one statement per line


 Capitalize initial keyword
 Keep statements language independent
 Indent to show hierarchy
 End multiline structures

-19-
0

Pseudo-code Example

BEGIN
READ sheets
stamps = sheets/5
ROUND stamps to next integer
DISPLAY stamps
END

-20-
Pseudo-code: Example 2

 Pseudo-code of a program that accepts two numbers


from the user and calculates their sum and product.
BEGIN
DISPLAY “Input two numbers”
READ num1, num2
sum=num1+num2
PRINT “ The sum is “, sum
product=num1*num2
PRINT “The product is “, product
END
-21-
Design Structures

Previous examples
followed sequence
structure

Sequence

One statement is executed after another •

Selection/Decision

Statements can be executed or skipped •


depending on whether a condition evaluates to
True or False

Repetition

Statements are executed repeatedly until a •


condition evaluates to True or False
Flowchart Constructs
Sequence Structure: Example 1

 Design an algorithm that displays the average of any three


numbers
START

Read
BEGIN x, y, z
READ x, y, z
avg = (x+y+z)/3 avg = (x+y+z)/3
PRINT avg
END Print
avg

STOP

-24-
Sequence Structure: Example 2

 Design an algorithm that reads the two sides of a rectangle and


calculates its area.
START

Read
BEGIN width, length
READ width, length
area=length*width area = length * width
PRINT area
END Print
area

STOP

-25-
2. Selection Structure

 IF-THEN STRUCTURE
 The IF-THEN statement allows us to choose whether
to execute a set of program statements based on a
test.

IF condition THEN Statement


Statement
ENDIF

-26-
Selection Structure

 IF–THEN–ELSE STRUCTURE

IF condition THEN
True alternative
ELSE
False alternative
False True
alternative alternative

ENDIF

End multiline structures


Indent to show hierarchy
-27-
Relational Operators

Operator Description
> Greater than
< Less than
= Equal to
>= Greater than or equal to
<= Less than or equal to
<> Not equal to

-28-
Selection Structure : Example 1

 An algorithm that prints the larger of two numbers.


START
BEGIN
READ a, b Read a, b a=b ??
IF a>b THEN
PRINT a
F T
ELSE if
PRINT b a>b
ENDIF
END Print b Print a

STOP -29-
Selection Structure: Example 2

Example: Student passes if the average score of his


four subjects 60 or more. START

BEGIN Read
READ m1, m2, m3, m4 m1,m2,m3,m4

SET score = (m1+m2+m3+m4)/4


score =(m1+m2+m3+m4)/4
IF score < 60 THEN
Print “Fail”
F IF T
ELSE
score <60
Print “Pass”
ENDIF Print Print
“Pass” “Fail”
END

STOP -30-
Selection Structure: Example 3

 An algorithm that reads an integer and prints if it is


even or odd. START
BEGIN
READ number Input number
IF number%2 = 0 THEN
PRINT “Even number”
ELSE False number%2 True
= 0
PRINT “odd number”
ENDIF
Print Print
END
“Odd number” “Even number”

END -31-
IF – ELSE IF Ladder

 Decision with multiple IF condition1 THEN


alternatives. Statement1
 The conditional expressions ELSE IF condition2 THEN
are evaluated from the top Statement2
downward. ELSE IF condition3 THEN
Statement3
 As soon as a true condition

is found, the statement ELSE
associated with it is Statement_n
executed, and the rest of ENDIF
the ladder is bypassed

-32-
IF – ELSE IF Ladder

-33-
IF – ELSE IF Ladder
BEGIN
READ temp
IF temp <= 0 THEN
A program that provides WRITE “Frozen”
weather prediction ELSE IF temp <= 12 THEN
WRITE “Cold”
according to expected ELSE IF temp <= 25 THEN
WRITE “Warm”
temperature. ELSE IF temp <= 75 THEN
WRITE “Hot”
ELSE IF temp <= 100 THEN
WRITE “Very hot”
ELSE
WRITE “ Burning”
ENDIF
END

-34-
Nested IF

 Multiple decisions
(if statement inside
another).

-35-
Nested IF: Example

A company has two payment policies. Some


employees have fixed monthly salary, while
some are paid on an hourly basis.

 A rate is fixed for one working hour.

 Employees paid on an hourly basis who exceed 40


working hours get a bonus for the extra hours (at
1.5 times the hourly rate).

-36-
Nested IF: Example

IF PAYTYPE= “HOURLY” THEN


IF HOURS>40 THEN
PAY = RATE * (40 +1.5 * (HOURS-40))
ELSE
PAY = RATE * HOURS
ENDIF
ELSE
PAY = SALARY
ENDIF

-37-
Exercise
LARGEST OF 3 NUMBERS.
True: The Largest
is Num1
True Num1>Num3?
False: The Largest
Num1>Num2 is Num3
? True: The Largest
False is Num2
Num2>Num3?
(Num2>=Num1) False: The Largest
is Num3
Solution - Pseudocode

IF Num1>Num2 THEN
IF Num1>Num3 THEN
Big = Num1
ELSE
Big = Num3
ENDIF
ELSE
IF Num2>Num3THEN
Big =Num2
ELSE
Big =Num3
ENDIF
ENDIF
-39-
Solution - Flowchart

-40-
Another Solution

BEGIN
READ Num1, Num2, Num3
Big = Num1
IF Num2 > Big THEN
Big = Num2
ENDIF
IF Num3 > Big THEN
Big = Num3
ENDIF
WRITE Big
END
-41-
Logical Operators

Operator Example Meaning

AND A < B AND B < C Result is True if both A<B


and B<C are true else false

OR A< B OR B < C Result is True if either A<B


or B<C are true else false

NOT NOT (A >B) Result is True if A>B is false


else true

-42-
Problem: Largest of three numbers

BEGIN
READ Num1, Num2, Num3
IF Num1>Num2 AND Num1>Num3 THEN
Big = Num1
ELSE IF Num2>Num1 AND Num2>Num3 THEN
Big = Num2
ELSE
Big = Num3
ENDIF
WRITE Big
END
-43-
Case Selection

 Repeating the IF … ELSE statements a number of


times can be somewhat confusing.

 An alternative method provided in a number of


languages is to use a selector determined by the
alternative fixed values.

 Selection structures are called case selection


structures when there are two or more
alternatives (constants) to choose from.

-44-
Case Selection

1 2 3 4

-45-
Case Selection

CASE OF VARIABLE
= constant1 :
actions for VARIABLE = constant1
= constants2 :
actions for VARIABLE = constant2

OTHERWISE:
Actions for VARIABLE = anything else
END-OF-CASE

-46-
Case Selection: Example 1
 An algorithm that provides recommendations for
hotels by interpreting the hotel stars ratings made by
users.
CASE OF rate
= 1:
Display “very bad, not recommended”
= 2:
Display “bad choice”
= 3:
Display “good but could be better”
= 4:
Display “very good”
= 5:
Display “excellent, highly recommended”
OTHERWISE
Display “invalid entry”
END-OF-CASE
-47-
Case Selection: Example 1 Cont.

CASE OF
rate

=1 =2 =3 =4 =5 OTHERWISE

Display Display Display Display


Display Display
“very “bad “very “Invalid
“good” “excellent”
bad” choice” good” ”

-48-
Another Solution: rate = 1
True Display
Using IF- ELSE IF “very bad”
False
IF rate = 1 THEN
True
Display “very bad, not recommended” Display “bad
rate = 2
ELSE IF rate = 2 THEN choice”
Display “bad choice”
ELSE IF rate = 3 THEN False
Display “good but could be better” True
Display
ELSE IF rate = 4 THEN rate = 3 “good”
Display “very good”
ELSE IF rate = 5THEN False
Display “excellent, highly recommended True
Display “very
ELSE rate = 4
good”
Display “invalid entry”
ENDIF False
True
rate = 5 Display
“excellent”
False
Display
“Invalid” -49-
Exercise: Complete

1. The algorithms can be designed through the use of -----


or -----.
2. The ----- has two exit points; these can be on the sides or
the bottom and one side.
3. Selection structures are called ----- selection structures
when there are two or more constants to choose from.
4. In flowchart, the ----- symbol is used to ask a question
that can be answered with binary format.
5. The ----- are used in case an upward flow will traverse
more than three symbols.

-50-
Practice – Design An algorithm for:

1. A program that reads two integers and prints if the


first is a multiple of the second.
2. A program that reads three integers and prints the
smallest
3. A program that assigns letter grades for a quiz,
according to the following table:
Score Grade
90 – 100 A
80 – 89 B
70 - 79 C
60 -69 D
< 60 F
-51-
-52-

You might also like