55
ALGORITHMS AND FLOWCHARTS

Programming fundamentals lecture 4

Embed Size (px)

Citation preview

Page 1: Programming fundamentals lecture 4

ALGORITHMS AND FLOWCHARTS

Page 2: Programming fundamentals lecture 4

ALGORITHMS AND FLOWCHARTS

• A typical programming task can be divided into two phases:

• Problem solving phase– produce an ordered sequence of steps that describe

solution of problem– this sequence of steps is called an algorithm

• Implementation phase – implement the program in some programming language

Page 3: Programming fundamentals lecture 4

Steps in Problem Solving

• First produce a general algorithm (one can use pseudocode)

• Refine the algorithm successively to get step by step detailed algorithm that is very close to a computer language.

• Pseudocode is an artificial and informal language that helps programmers develop algorithms. Pseudocode is very similar to everyday English.

Page 4: Programming fundamentals lecture 4

Pseudocode & Algorithm

• Example 1: Write an algorithm to determine a student’s final grade and indicate whether it is passing or failing. The final grade is calculated as the average of four marks.

Page 5: Programming fundamentals lecture 4

Pseudocode & Algorithm

Pseudocode:• Input a set of 4 marks• Calculate their average by summing and dividing by 4• if average is below 50

Print “FAIL”else

Print “PASS”

Page 6: Programming fundamentals lecture 4

Pseudocode & Algorithm

• Detailed Algorithm • Step 1: Input M1,M2,M3,M4

Step 2: GRADE (M1+M2+M3+M4)/4 Step 3: if (GRADE < 50) then

Print “FAIL” else

Print “PASS”endif

Page 7: Programming fundamentals lecture 4

The Flowchart

A Flowchart– shows logic of an algorithm– emphasizes individual steps and their

interconnections– e.g. control flow from one action to the next

Page 8: Programming fundamentals lecture 4

Flowchart Symbols

Basic

Oval

Parallelogram

Rectangle

Diamond

Hybrid

Name Symbol Use in Flowchart

Denotes the beginning or end of the program

Denotes an input operation

Denotes an output operation

Denotes a decision (or branch) to be made. The program should continue along one of two routes. (e.g. IF/THEN/ELSE)

Denotes a process to be carried oute.g. addition, subtraction, division etc.

Flow line Denotes the direction of logic flow in the program

Page 9: Programming fundamentals lecture 4

Example

PRINT“PASS”

Step 1: Input M1,M2,M3,M4Step 2: GRADE (M1+M2+M3+M4)/4 Step 3: if (GRADE <50) then

Print “FAIL” else

Print “PASS” endif

START

InputM1,M2,M3,M4

GRADE(M1+M2+M3+M4)/4

ISGRADE<50

PRINT“FAIL”

STOP

YN

Page 10: Programming fundamentals lecture 4

Example 2

• Write an algorithm and draw a flowchart to convert the length in feet to centimeter.

Pseudocode:• Input the length in feet (Lft)• Calculate the length in cm (Lcm) by multiplying

LFT with 30• Print length in cm (LCM)

Page 11: Programming fundamentals lecture 4

Example 2

Algorithm • Step 1: Input Lft• Step 2: Lcm Lft x 30 • Step 3: Print Lcm

START

InputLft

Lcm Lft x 30

PrintLcm

STOP

Flowchart

Page 12: Programming fundamentals lecture 4

Example 3

Write an algorithm and draw a flowchart that will read the two sides of a rectangle and calculate its area.

Pseudocode • Input the width (W) and Length (L) of a rectangle• Calculate the area (A) by multiplying L with W• Print A

Page 13: Programming fundamentals lecture 4

Example 3

Algorithm • Step 1: Input W,L• Step 2: A L x W • Step 3: Print A

START

InputW, L

A L x W

PrintA

STOP

Page 14: Programming fundamentals lecture 4

Example 4

• Write an algorithm and draw a flowchart that will calculate the roots of a quadratic equation

• X=(-b + sqrt (b2 -4ac))/2a• X=(-b - sqrt (b2 -4ac))/2a

2 0ax bx c

Page 15: Programming fundamentals lecture 4

Example 4

Pseudocode: • Input the coefficients (a, b, c) of the quadratic

equation• Calculate d• Calculate x1• Calculate x2• Print x1 and x2

Page 16: Programming fundamentals lecture 4

Example 4

• Algorithm: • Step 1: Input a, b, c• Step 2: d sqrt ( )• Step 3: x1 (–b + d) / (2 x a)• Step 4: x2 (–b – d) / (2 x a)• Step 5: Print x1, x2

START

Inputa, b, c

d sqrt(b x b – 4 x a x c)

Printx1 ,x2

STOP

x1 (–b + d) / (2 x a)

X2 (–b – d) / (2 x a)

4b b a c

Page 17: Programming fundamentals lecture 4

DECISION STRUCTURES

• The expression A>B is a logical expression• 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• print the value of A • if A>B is false (if A is not greater than B) we take the

action on right• print the value of B

Page 18: Programming fundamentals lecture 4

DECISION STRUCTURES

isA>B

Print BPrint A

Y N

Page 19: Programming fundamentals lecture 4

IF–THEN–ELSE STRUCTURE

• The structure is as followsIf condition then

true alternative else

false alternativeendif

Page 20: Programming fundamentals lecture 4

IF–THEN–ELSE STRUCTURE

• The algorithm for the flowchart is as follows:If A>B then

print Aelse

print Bendif

isA>B

Print BPrint A

Y N

Page 21: Programming fundamentals lecture 4

Relational Operators

Relational Operators

Operator Description> Greater than

< Less than

= Equal to

Greater than or equal to Less than or equal to

Not equal to

Page 22: Programming fundamentals lecture 4

Example 5 • Write an algorithm that reads two values, determines the

largest value and prints the largest value with an identifying message.

ALGORITHMStep 1: Input VALUE1, VALUE2Step 2: if (VALUE1 > VALUE2) then

MAX VALUE1else

MAX VALUE2endif

Step 3: Print “The largest value is”, MAX

Page 23: Programming fundamentals lecture 4

Example 5

MAX VALUE1

Print“The largest value is”, MAX

STOP

Y N

START

InputVALUE1,VALUE2

MAX VALUE2

isVALUE1>VALUE2

Page 24: Programming fundamentals lecture 4

NESTED IFS

• One of the alternatives within an IF–THEN–ELSE statement– may involve further IF–THEN–ELSE statement

Page 25: Programming fundamentals lecture 4

Example 6

• Write an algorithm that reads three numbers and prints the value of the largest number.

Page 26: Programming fundamentals lecture 4

Example 6Step 1: Input N1, N2, N3Step 2: if (N1>N2) then

if (N1>N3) then MAX N1 [N1>N2, N1>N3]

else MAX N3 [N3>N1>N2]

endifelse

if (N2>N3) then MAX N2 [N2>N1, N2>N3]

else MAX N3 [N3>N2>N1]

endifendif

Step 3: Print “The largest number is”, MAX

Page 27: Programming fundamentals lecture 4

Example 6

• Flowchart: Draw the flowchart of the above Algorithm.

Page 28: Programming fundamentals lecture 4

Example 7

• Write and algorithm and draw a flowchart to a) read an employee name (NAME), overtime

hours worked (OVERTIME), hours absent (ABSENT) and

b) determine the bonus payment (PAYMENT).

Page 29: Programming fundamentals lecture 4

Example 7

Bonus Schedule

OVERTIME – (2/3)*ABSENT Bonus Paid

>40 hours>30 but 40 hours>20 but 30 hours>10 but 20 hours 10 hours

$50$40$30$20$10

Page 30: Programming fundamentals lecture 4

Step 1: Input NAME,OVERTIME,ABSENTStep 2: if (OVERTIME–(2/3)*ABSENT > 40) then PAYMENT 50 else if (OVERTIME–(2/3)*ABSENT > 30) then

PAYMENT 40 else if (OVERTIME–(2/3)*ABSENT > 20) then PAYMENT 30 else if (OVERTIME–(2/3)*ABSENT > 10) then PAYMENT 20 else PAYMENT 10 endif

Step 3: Print “Bonus for”, NAME “is $”, PAYMENT

Page 31: Programming fundamentals lecture 4

Example 7

• Flowchart: Draw the flowchart of the above algorithm?

Page 32: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

32

Objectives

• In this chapter you will be able to:

• Introduce common words, keywords, and meaningful names when writing pseudocode

• Define the three basic control structures as set out in the Structure Theorem

• Illustrate the three basic control structures using pseudocode

Page 33: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

33

• When designing a solution algorithm, you need to keep in mind that a computer will eventually perform the set of instructions written

• If you use words and phrases in the pseudocode which are in line with basic computer operations, the translation from pseudocode algorithm to a specific programming language becomes quite simple

How to Write Pseudocode

Page 34: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

34

Six Basic Computer Operations

1 A computer can receive information– When a computer is required to receive

information or input from a particular source, whether it is a terminal, a disk or any other device, the verbs Read and Get are used in pseudocode

Read => Input from a recordGet => Input from keyboard

Example pseudocode

Read student nameGet system dataRead number1, number2Get tax_code

Page 35: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

35

Six Basic Computer Operations

1 A computer can receive information– Usually an output Prompt instruction is required

before an input Get instruction

Example pseudocode

Prompt for student_markGet student_mark

Page 36: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

36

Six Basic Computer Operations

2 A computer can put out information– When a computer is required to supply

information or output to a device, the verbs Print, Write, Put, Output, or Display are used in pseudocode

– Print => send output to printer– Write => send out to file– Put, Output, Display => send to screen

Example pseudocodePrint ‘Program Completed’Write customer record to master fileOutput total taxDisplay ‘End of data’

Page 37: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

37

Six Basic Computer Operations3 A computer can perform arithmetic

– Most programs require the computer to perform some sort of mathematical calculation, or formula, and for these, a programmer may use either actual mathematical symbols or the words for those symbols

– To be consistent with high-level programming languages, the following symbols can be written in pseudocode:+ for Add - for Subtract* for Multiply / for Divide ( ) for Parentheses

– When writing mathematical calculations for the computer, standard mathematical ‘order of operations’ applies to pseudocode and most computer languages

Page 38: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

38

Six Basic Computer Operations

4 A computer can assign a value to a variable or memory location

– There are three cases where you may write pseudocode to assign a value to a variable or memory location:

1. To give data an initial value in pseudocode, the verbs Initialize or Set are used

2. To assign a value as a result of some processing the symbols ‘=‘ or ‘’ are written

3. To keep a variable for later use, the verbs Save or Store are used

Page 39: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

39

Six Basic Computer Operations

4 A computer can assign a value to a variable or memory location

Example pseudocode

Initialize total_price to zeroSet student_count to zeroTotal_price = cost_price + sales_taxTotal_price cost_price + sales_taxStore customer_num in last_customer_num

Page 40: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

40

Six Basic Computer Operations

5 A computer can compare two variables and select one or two alternate actions

– An important computer operation available to the programmer is the ability to compare two variables and then, as a result of the comparison, select one of two alternate actions

– To represent this operation in pseudocode, special keywords are used: IF, THEN, and ELSE

Page 41: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

41

Six Basic Computer Operations

6 A computer can repeat a group of actions

– When there is a sequence of processing steps that need to be

repeated, two special keywords, DOWHILE and ENDDO, are

used in pseudocode

– The condition for the repetition of a group of actions is

established in the DOWHILE clause, and the actions to be

repeated are listed beneath it

Page 42: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

42

Meaningful Names• All names should be meaningful• A name given to a variable is simply a method of identifying a particular

storage location in the computer• The uniqueness of a name will differentiate it from other locations• Often a name describes the type of data stored in a particular variable• Most programming languages do not tolerate a space in a variable name,

as a space would signal the end of the variable name and thus imply that there were two variables

Page 43: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

43

The Structure Theorem

• The Structure Theorem states that it is possible to write any computer program by using only three basic control structures that are easily represented in pseudocode: – Sequence– Selection– Repetition

Page 44: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

44

The Three Basic Control Structures1 Sequence

– The sequence control structure is the straightforward execution of one processing step after another

– In pseudocode, we represent this construct as a sequence of pseudocode statements

2 Selection– The selection control structure is the presentation of a condition and the

choice between two actions; the choice depends on whether the condition is true or false

– In pseudocode, selection is represented by the keywords IF, THEN, ELSE, and ENDIF

Page 45: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

45

The Three Basic Control Structures

3 Repetition

– The repetition control structure can be defined as the presentation of a set of instructions to be performed repeatedly, as long as a condition is true

– The basic idea of repetitive code is that a block of statements is executed again and again, until a terminating condition occurs

– This construct represents the sixth basic computer operation, namely to repeat a group of actions

Page 46: Programming fundamentals lecture 4

Simple Program Design, Fourth Edition Chapter 2

46

Summary• In this chapter, six basic computer operations were listed, along

with pseudocode words and keywords to represent them

• These operations were: to receive information, put out information, perform arithmetic, assign a value to a variable, decide between two alternate actions, and repeat a group of actions

• The Structure Theorem was introduced; it states that it is possible to write any computer program by using only three basic control structures: sequence, selection, and repetition

Page 47: Programming fundamentals lecture 4

Someone Stole a Cookie from the Cookie Jar

Problem: Momma had just filled the cookie jar when the 3 children went to bed. That night one child woke up, ate half of the cookies and went back to bed. Later, the second child woke up, ate half of the remaining cookies, and went back to bed. Still later, the third child woke up, ate half of the remaining cookies, leaving 3 cookies in the jar. How many cookies were in the jar to begin with?

Page 48: Programming fundamentals lecture 4

Someone Stole a Cookie from the Cookie Jar (cont’d)

• Information available:– Three children– Each one ate half of the cookies– Three cookies remaining

• Information needed:– Original number of cookies

• Calculations:– For each child, multiply the number of remaining cookies

by two.

Page 49: Programming fundamentals lecture 4

Specific Solution to the Problem• First, we solve the specific problem to help us

identify the steps.

– 3 cookies left X 2 = 6 cookies left after 2nd child

– 6 X 2 = 12 cookies left after 1st child– 12 X 2 = 24 = original number of cookies

Page 50: Programming fundamentals lecture 4

A Generic Algorithm

• What is a generic algorithm for this problem?

An algorithm that will work with any number of remaining cookies

ANDthat will work with any number of children.

Page 51: Programming fundamentals lecture 4

Generic Algorithm for Cookie Problem

• Get number of children.• Get number of cookies remaining.• While there are still children that have not

raided the cookie jar, multiply the number of cookies by 2 and reduce the number of children by 1.

• Display the original number of cookies.

Page 52: Programming fundamentals lecture 4

Test The Generic Algorithm

• Try the algorithm on paper with:– Four children and six cookies remaining.– Two children with two cookies remaining.

• If you did not get the correct answer, modify the algorithm so that you get the correct answer.

Page 53: Programming fundamentals lecture 4

Pseudocode• When we broke down the previous problem

into steps, we expressed each step as an English phrase.

• We can think of this as writing pseudocode for the problem.

• Typically, pseudocode is a combination of English phrases and formulas.

Page 54: Programming fundamentals lecture 4

Pseudocode (con’t)• Pseudocode is used in

– designing algorithms– communicating an algorithm to the customer– converting an algorithm to code (used by the

programmer)– debugging logic (semantic) errors in a solution

before coding (hand tracing)• Let’s write the Cookie Problem algorithm using

a more formal pseudocode and being more precise.

Page 55: Programming fundamentals lecture 4

Improved PseudocodeDisplay “Enter the number of children: “Read <number of children>Display “Enter the number of cookies remaining: “Read <cookies remaining><original cookies> = <cookies remaining>While (<number of children> > 0)

<original cookies> = <original cookies> X 2<number of children> = <number of children> - 1

End_WhileDisplay “Original number of cookies = “, <original cookies>