comp 151 introduction to algorithms and programming · the key features of an algorithm •...

21
1 College of Arts and Sciences Department of Mathematical and Physical Sciences Computer Science Section Spring 2011-2012 COMP 151 Introduction to Algorithms and Programming (3 Hours Lectures and 2 Hours lab) Mr.Lohani Adeeb Khan

Upload: others

Post on 07-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

1

College of Arts and Sciences

Department of Mathematical and Physical Sciences Computer Science Section

Spring 2011-2012

COMP 151 Introduction to Algorithms and

Programming

(3 Hours Lectures and 2 Hours lab)

Mr.Lohani Adeeb Khan

Page 2: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

2

CHAPTER 1

INTRODUCTION TO

ALGORITHMS

Page 3: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

3

Algorithms and Humans Algorithms are not a natural way of stating a problem’s solution, because we do not normally state our plan of action. We tend to execute as we think about the problem. Hence, there are inherent difficulties when writing an algorithm. We normally tailor our plans of action to the particular problem at hand and not to a general problem (i.e. a nearsighted approach to problem solving). We usually do not write out our plan, because we are usually unaware of the basic ideas we use to formulate the plan. We hardly think about it – we just do it. Computer programmers need to adopt a scientific approach to problem solving, i.e. writing algorithms that are comprehensive and precise. We need to be aware of the assumptions we make and of the initial conditions. Be careful not to overlook a step in the procedure just because it seems obvious. Remember, machines do not have judgment, intuition or common sense! Problem: In a place 4095 bananas were there. First a Monkey came and it ate a single banana, second monkey ate twice of the first monkey, and third monkey ate twice of the second monkey….its going on. At a particular stage all the bananas were exactly (no fraction) eaten by some number of monkeys. How many monkeys came there? Problem: The number 45 is broken into four parts such as part1=X + 2, part2=X – 2, part3=X * 2, and part4=X / 2. In all the parts X is same. Find the value of X.

Page 4: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

4

What is an Algorithm?

An Algorithm is a sequence of unambiguous instructions for solving a problem, i.e., for obtaining a required output for any legitimate input in a finite amount of time

Is any well-defined computational procedure that takes some value, or set of values, as input and produces some value, or set of values, as output.

More precisely, an algorithm is a method or process to solve a problem satisfying the following properties:

Finiteness – terminates after a finite number of steps

Definiteness – Each step must be carefully and clearly

specified. Input

– Valid inputs must be clearly specified. Output

– Can be proved to produce the correct output given a valid can be proved to produce the correct output given a valid input.

Effectiveness – Steps must be sufficiently simple and basic.

“Computer”

Problem

Algorithm

Input Output

Page 5: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

5

Basic (primitive) operations involved • Read the input from user • Carry out basic arithmetical computations • Print the output to the user

Variables A variable is a symbolic name assigned to a data item by the programmer. At any particular time, a variable will stand for one particular data, called the value of a variable, which may change from time to time during a computing process. The value of a variable may change many times during the execution of a program. A variable is usually given a name by the programmer. A named location that stores a value

A = 5 B = 3 A C = A + B B = 4 C = A + B A = 7 B A = A + 3 A = A + C C

Arithmetic operators

+ add - subtract * multiply / divide = assign % mod

Page 6: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

6

Relational operators = = Equal to > Greater than < Less than >= Greater than or equal <= Less than or equal != Not equal to Logical operators

&& AND || OR ! NOT

Examples: IF (x = = 32) && (y = = 7) THEN sum = x + y IF (letter = = 'A') || (letter = = 'E') THEN DISPLAY 'Vowel‘ IF (letter != 'A') THEN DISPLAY 'Not letter A' The key features of an algorithm

• Sequence (also known as Process) • Decision (also known as Selection) • Repetition (also known as Iteration or Looping)

Sequence (Process): Instructions are written one by one Example: Write an algorithm to add two numbers

Start Step 1: Get number1 Step 2: Get number2 Step 3: Sum=number1 + numbert2 Step 4: Display/Print sum Stop

Page 7: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

7

Decision (Selection): Instructions are written based on some conditions. If the particular condition or conditions are satisfied then the program flow is in one route. Otherwise it follows another route. ie, based on conditions the selection of program flow is jumped into some ways. Conditionals Statement implemented if condition is true A=1, B=2, C=3, D=4 if A < B C = 5 A if A > B D = 4 B if C < D B = B + 1 C Else B = B - 1 D Example: Write and algorithm to compare two numbers and print the smallest number

Start: Step 1: Get number1 Step 2: Get number2 Step 3: If number1< number2 Step 4: print number1 is smaller Step 5: else print number2 is smaller. Stop

1

2

3

4

Page 8: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

8

Repetition (Looping): In some of the program the same steps are repeated for number of times. In that case the looping structure helps us to do the work. Basically we will study about While loop, Do...While loop and For loop structure. Based on some condition or conditions the iteration is worked out. Example: Computing the Greatest Common Divisor of Two Integers Problem definition:

Greatest Common Divisor (GCD) of two non-negative, not-both-zero integers m and n, denoted by gcd(m, n), is defined as the largest integer that divides both m and n evenly, i.e. with remainder of zero Euclid’s algorithm: gcd(m, n) = gcd(n, m mod n) Eg. gcd(60,24) = gcd(24,12) = gcd(12, 0) = 12

Start Step 1: If n = 0, return the value of m as the answer and

go to Stop; otherwise, proceed to Step 2. Step 2: Divide m by n and assign the value of the

remainder to r. Step 3: Assign the value of n to m and the value of r to n.

Go to Step 1. Stop

Methods of Specifying an Algorithm

• There are two commonly used tools to help to document program logic (the algorithm).

These are 1. Pseudocode. 2. Flowchart.

• We will use both methods here. Generally, flowcharts work well for small problems but Pseudo code is used for larger problems.

Page 9: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

9

Pseudocode • Pseudocode is a more simplified version of an

algorithm. • A mixture of a natural language and programming

language • Allows the designer to focus on the logic of the

algorithm without being distracted by details of language syntax.

How to write Pseudocode An algorithm can be written in pseudocode using six (6) basic computer operations:

1. A computer can receive information. Typical pseudocode instructions to receive information are:

Read name Get name Read number1, number2

2. A computer can output (print) information. Typical pseudocode instructions are: Print name

Display Number Write "The average is", avg

3. A computer can perform arithmetic operation Typical pseudocode instructions:

Add number to total, or Total = Total + Number Avg = sum/total

4. A computer can assign a value to a piece of data Typical pseudocode e.g. to assign/give data an initial value:

Initialize total to zero Set count to 0 To assign a computed value: Total = Price + Tax

Page 10: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

10

5. Computer can compare two (2) pieces of information and select one of two actions.

Typical pseudocode e.g. IF number < 0 then add 1 to neg_number ELSE add one to positive number End-if

6. A computer can repeat a group of actions. Typical pseudocode e.g.

REPEAT until total = 50 read number write number add 1 to total

End-repeat (OR) WHILE total < = 50 do:

read number write number add 1 to total

End-while Example Problem: Read the ‘N’ Number of values and find the Average of these values Pseudocode Header: Algorithm Average Description: This algorithm reads a list of numbers and computes their average. Let: SUM be the total of the numbers read COUNTER to count the number of items in the list AVG be the average of all the numbers Number be the value of element N be the number of elements

Page 11: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

11

Body: Start Step 1: Set SUM to 0, Set COUNTER to 0. (i.e. initialize variables) Step 2: Read N Step 3: While N > 0 do Step 4: Read Number Step 5: Print Number Step 6: COUNTER=COUNTER + 1 (i.e. increment the COUNTER by 1) Step 7: SUM = SUM + Number (i.e. add number to SUM, storing result in SUM) Step 8: N=N-1 end-while Step 9: if COUNTER = = 0 then Step 10: AVG = 0 else Step 11: AVG = SUM / COUNTER end-if Step 12: Print the SUM Step 13: Print the AVG Stop. Problem: Design a program which accepts as input two numbers and calculates sum and difference and then displays both the sum and the difference. Pseudocode: Body Start Step1: Read Number1 Step2: Read Number2 Step3: Sum = Number1 + Number2 Step4: Difference = Number1 - Number2 Step5: DISPLAY Sum Step6: DISPLAY Difference Stop

Page 12: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

12

Flowchart: A method of expressing an algorithm by a collection of connected geometric shapes containing descriptions of the algorithm’s steps

Page 13: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

13

Example: A flowchart that reads the name of 30 students in the class and displays it

Display the name of the student

If number of students<=30

Yes

No

Start

Stop

Read the name of the student

Increase the number of students by 1

Set number of students=1

Page 14: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

14

Pseudocode: Start Step 1: Set the number of students=1 Step 2: Repeat until number of students<=30 Step 3: Read the Name of the student Step 4: Display the Name of the student Step 5: Increase the number of students by 1 Step 6: End Repeat Stop Example: GCD of two Numbers Pseudocode Start Step 1: Read m, n Step 2: Repeat until n!=0 Step 3: r=m%n Step 4: m=n Step 5: n=r Step 6: End Repeat Step 7: Display ‘m’ as the GCD Stop Problem: Draw the Flowchart for the above Pseudocode. Problem: Draw a flow chart that accepts two numbers and displays the sum Problem: Draw a flowchart for the problem that is accepting two numbers and calculating sum and difference and then displaying the result Example: Draw a flowchart to add all the numbers from 1 to 20.

Page 15: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

15

Pseudocode:

Start Step 1: Set Number=1 Step 2: Set Sum=0 Step 3: Repeat until Number<=20 Step 4: Sum=Sum + Number Step 5: Number= Number + 1 Step 6: End Repeat Step 7: Display Sum Stop

Display Sum

Number =1

If Number<=20

Sum=Sum+Number

Sum =0

Number =Number+1

Yes

No

Stop

Start

Page 16: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

16

Example: Flow chart for Average of 3 Numbers

Example: A program has to be written to display the grades of the students in a class of 30 students. Grade is calculated on the basis of percentage (%) marks obtained by the student.

• More than or equal to 80% A • More than or equal to 60% B • More than or equal to 50% C • More than or equal to 40% D • Less than 40% F (Fail) • Draw a flowchart and write the corresponding algorithm

Page 17: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

17

Mark>=80?

Read the mark of the Student

Mark>=60?

Mark>=50?

Mark>=40?

If Number of Students<=30

Display Grade A

Display Grade D

Display Grade B

Display Grade C

Display Grade F

Yes

Yes

Yes

Yes No

No

No

No

Yes

No

Stop

Start

Increase the Number of Students by one

Set Number of students=1

Page 18: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

18

Pseudocode: Start Step 1: Set Number of Students=1 Step 2: Repeat Until Number of Students<=30 Step 3: Get the Mark of the student Step 4: Check Mark >= 80 Step 5: If yes Display Grade is ‘A’ then go to Step 13 Step 6: Otherwise Check Mark >= 60 Step 7: If yes Display Grade is ‘B’ then go to Step 13 Step 8: Otherwise Check Mark >= 50 Step 9: If yes Display Grade is ‘C’ then go to Step 13 Step 10: Otherwise Check Mark >= 40 Step 11: If yes Display Grade is ‘D’ then go to Step 13 Step 12: Otherwise Display Grade ‘F’ Step 13: Increase the Number of Students by one Step 14: End Repeat Stop

Page 19: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

19

Example: Draw a flowchart that accepts 3 numbers say x, y, and z from the user and finds the largest number.

If x > y

Display z is largest

If y > z

If x > z Display x is largest

Display y is largest

Get x, y, z

No No

Yes Yes

Yes

No

Stop

Start

Page 20: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

20

Pseudocode: Start Step 1: Read the values x, y and z Step 2: Check x > y Step 3: If yes, Check x > z

Step 3.1: If yes, Display ‘x’ is largest then go to Stop Step 3.2: Otherwise Display ‘z’ is largest then go to Stop

Step 4: Otherwise Check y > z Step 4.1: If yes Display ‘y’ is largest then go to Stop Step 4.2: Otherwise Display ‘z’ largest then go to Stop

Stop General Rules for flowcharting

1. All boxes of the flowchart are connected with Arrows. (Not lines).

2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit point for all flowchart symbols is on the bottom except for the Decision symbol.

3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.

4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown as long as it does not exceed 3 symbols.

5. Connectors are used to connect breaks in the flowchart. Examples are:

• From one page to another page. • From the bottom of the page to the top of the

same page. 6. Subroutines (Functions) and Interrupt programs have

their own and independent flowcharts. 7. All flow charts start with a Terminal symbol. However,

Subroutines or Functions or interrupt programs start with Predefined Process symbol.

8. All flowcharts end with a terminal.

Page 21: COMP 151 Introduction to Algorithms and Programming · The key features of an algorithm • Sequence (also known as Process) • Decision (also known as Selection) • Repetition

21

Exercises: 1. Draw the flowchart and write the algorithm to find the

given number is odd or even - 3 Marks 2. Draw the flowchart and write the algorithm to find the

square of the given number - 3 Marks 3. Draw the flowchart and write the algorithm to calculate

the area of the circle - 3 Marks 4. Draw the flowchart and write the algorithm to swap the

two numbers - 3 Marks 5. Draw the flowchart and write the algorithm to print the

Fibonacci Series 0,1,1,2,3,5,8,13,21 - 3 Marks 6. An electricity board charges the following rates to

domestic users to discourage large consumption of energy: - 3 Marks

For the first 100 units – 10 Paisa per unit For next 200 units – 20 Paisa per unit Beyond 300 units – 30 Paisa per unit

If the total cost is more than 10 OMR then an additional surcharge of 15% is added. Draw the flowchart and write the algorithm to calculate the amount for number of units consumed.

7. Draw the flowchart and write the algorithm to read 100 different numbers and then display the sum of numbers.

- 3 Marks 8. Draw the flowchart and write the algorithm to read two

numbers and then display the largest - 3 Marks 9. Draw the flowchart and write the algorithm to read two

numbers and then display the smallest - 3 Marks 10. Draw the flowchart and write the algorithm to read three

numbers and then display the smallest - 3 Marks