Sie sind auf Seite 1von 43

Fundamentals of Algorithms

LECTURE 02

IIT UST BANNU

Fundamentals of Algorithmds

Review of the Previous Lecture

What is computer Science? Some Misconception about Computer Science. What is an algorithm and how it is related to Computer Science? Types of Operations in Algorithms. Example of Algorithms in Real Life e.g. Human Genome project, Robots etc.

Fundamentals of Algorithmds

The Parts of an Algorithm


It is worthwhile to think about these algorithm related terms because we can rely on these when we write new algorithms. Common parts of algorithms include 1.Variables: Named Values 2.Parameters: Named Inputs 3.Conditionals: Handling Different Conditions 4.Repetition 5.Subroutines: Named Helper Algorithms 6.Recursion: Helping Yourself
Fundamentals of Algorithmds

Variables: Named Values

As we write algorithms, we like to name things. Sometimes we use long names, Sometimes, we use shorter names, As we start to write more formal algorithms, we may explicitly say that we're using names.

Fundamentals of Algorithmds

Parameters: Named Inputs

Many algorithms work on data that are passed to the algorithm. Similarly, an algorithm to find a name in the phone book might take the name and the phone book as input values. We call such input values parameters.

Fundamentals of Algorithmds

Conditionals: Handling Different Conditions

At times, our algorithms have to account for different conditions, doing different things depending on those conditions. We call such operations conditionals. They typically take either the form

Fundamentals of Algorithmds

Conditionals: Handling Different Conditions

if some condition holds then do something of the more complex form if some condition holds then do something otherwise do something else At times, we need to decide between more than two possibilities.

Fundamentals of Algorithmds

Repetition

At times, our algorithms require us to do something again and again. . We call this technique repetition. Repetition takes many forms. We might do work until we've reached a desired state.

Fundamentals of Algorithmds

Repetition

Repeat some action until some condition holds We might continue work as long as we're in some state. repeat some action while some condition holds We might repeat an action a fixed number of times. repeat some action N times You can probably think of other forms of repetition.

Fundamentals of Algorithmds

Subroutines: Named Helper Algorithms

Many algorithms require common actions for their operation. We can write additional algorithms for these common actions and use them as part of our broader algorithm. We can also use them in other algorithms. We call these helper algorithms subroutines. Just like functions in C++

Fundamentals of Algorithmds

Recursion: Helping Yourself

As strange as it may seem, we sometimes find it useful to define an algorithm in terms of itself. In particular, we can have an algorithm deal with a large or complex input by using itself as a helper with a smaller or less complex input.

Fundamentals of Algorithmds

Recursion: Helping Yourself

Consider the following example To make N peanut butter and jelly sandwiches If N is 0 then conditional Celebrate, you're done! Otherwise Make one PBJ sandwich subroutine Make N-1 PBJ sandwiches recursion

Fundamentals of Algorithmds

Recursion: Helping Yourself

We call this technique recursion. Mastering recursion is one of the key steps on your path to becoming a computer scientist.

Fundamentals of Algorithmds

Characteristics of an algorithm

Let us try to present the scenario of a man brushing his own teeth(natural denture) as an algorithm as follows. Step 1. Take the brush Step 2. Apply the paste Step 3. Start brushing Step 4. Rinse Step 5. Wash Step 6. Stop

Fundamentals of Algorithmds

Characteristics of Algorithms

An Algorithm should have the following five characteristics: 1. Input 2. Output 3. Definiteness 4. Effectiveness 5. Termination

Fundamentals of Algorithmds

Characteristics of Algorithms

Finiteness: It means that the algorithm terminates after a finite number of steps

Fundamentals of Algorithmds

Characteristics of Algorithms

Definiteness: Should have well defined and unambiguously specified steps.

Fundamentals of Algorithmds

Characteristics of Algorithms

Input: The algorithm should be given valid inputs and clearly specified. E.g. Student Record Search Algorithm

Fundamentals of Algorithmds

Characteristics of Algorithms

Output: It means that it can be proved to produce the correct output given a valid input

Fundamentals of Algorithmds

Characteristics of Algorithms

Effectiveness: steps are sufficiently simple and basic. It should effectively solve the problem within limited resources.

Fundamentals of Algorithmds

Characteristics of Algorithms

Termination: It means that the algorithm should terminate after completion of its task or failure (optional).

Fundamentals of Algorithmds

Ways of Expressing Algorithms

Pseudo code Flowchart

Fundamentals of Algorithmds

Whats Pseudocode ?
Artificial

and Informal language Helps programmers to plan an algorithm Similar to everyday English Not an actual programming language

Fundamentals of Algorithmds

E.g : Pseudocode
Read A, B Calculate C = A*B Display C Stop

Fundamentals of Algorithmds

Comparative Between Flowchart vs Pseudocode


Flowchart
A

graphical way of writing pseudocode Rounded rectangle terminal Parallelogram input / output Rectangle actions Diamonds decision / conditional Circles connector

Fundamentals of Algorithmds

E.g : Flowchart
Start

Start Terminal. Program start here Input. Enter values for A and B

Read A Read B

Calculate Resut C=A*B

Process

Display the Result C

Output

Stop

Stop Terminal Program end here

Fundamentals of Algorithmds

Comparative Between Flowchart vs Pseudocode (..Cont.)


Pseudocode
No

syntax rule Independent from any programming language Write in an ordinary language Uses a structure resembling computer structure No connector between pages

Fundamentals of Algorithmds

E.g : Pseudocode
Read A, B Input Calculate C = A*B - Action Display C - Output Stop - Terminal

Fundamentals of Algorithmds

Example 2 (Selection)
Read A, B
IF A is less than B

BIG = B SMALL = A ELSE BIG = A SMALL = B Write / Display BIG, SMALL Stop
Fundamentals of Algorithmds

Example 2 (Selection)
Read A, B - Input
IF A is less than B - Selection

BIG = B - Action SMALL = A - Action ELSE - Selection BIG = A - Action SMALL = B - Action Write / Display BIG, SMALL - Output Stop - Terminal
Fundamentals of Algorithmds

Example 3 (Repetition)
Set count to zero Set total to zero Read number WHILE ( not end-of-data ) increment count by 1 total = total + number read number IF ( count > 0 ) then average = total / count Display average Stop
Fundamentals of Algorithmds

Advantages
Converting

a pseudocode to a programming language is much more easier than converting a flowchart. As compared to flowchart, it is easier to modify a pseudocode of a program logic when program modifications are necessary.
Easily

modified Implements structured concepts Done easily on Word Processor


Fundamentals of Algorithmds

Limitations
In

the cases of pseudocode, a graphic representation of program logic is not available. There are no standard rules to follow for using a pseudocode.
Different

programmers use their own style of writing pseudocode; and hence, Communication problem occurs due to lack of standardization.
Fundamentals of Algorithmds

Basic Algorithm Writing Techniques

Fundamentals of Algorithmds

Rules for Pseudocode

Write only one statement per line

Capitalize initial keyword Indent to show hierarchy End multiline structures Keep statements language independent
Fundamentals of Algorithmds

One Statement Per Line


Each statement in pseudocode should express just one action for the computer. If the task list is properly drawn, then in most cases each task will correspond to one line of pseudocode.
Task List
Read name, hours worked, rate of pay Perform calculations gross = hours worked * rate of pay Write name, hours worked, gross

Pseudocode
READ name, hoursWorked, payRate gross = hoursWorked * payRate WRITE name, hoursWorked, gross

Fundamentals of Algorithmds

Capitalize Initial Keyword


In the example below note the words: READ and WRITE. These are just a few of the keywords to use, others include:
READ, WRITE, IF, ELSE, ENDIF, WHILE, ENDWHILE

Pseudocode
READ name, hoursWorked, payRate gross = hoursWorked * payRate WRITE name, hoursWorked, gross
Fundamentals of Algorithmds

Indent to Show Hierarchy


Each design structure uses a particular indentation pattern

Sequence:
Keep statements in sequence all starting in the same column

Selection:
Indent statements that fall inside selection structure, but not the keywords that form the selection

Loop:
Indent statements that fall inside the loop but not keywords that form the loop
READ name, grossPay, taxes IF taxes > 0 net = grossPay taxes ELSE net = grossPay ENDIF WRITE name, net

Fundamentals of Algorithmds

End Multiline Structures


READ name, grossPay, taxes

IF taxes > 0 net = grossPay taxes ELSE net = grossPay ENDIF WRITE name, net

See the IF/ELSE/ENDIF as constructed above, the ENDIF is in line with the IF. The same applies for WHILE/ENDWHILE etc
Fundamentals of Algorithmds

Language Independence
Resist the urge to write in whatever language you are most comfortable with, in the long run you will save time. Remember you are describing a logic plan to develop a program, you are not programming!

Fundamentals of Algorithmds

The Selection Structure


yes amount < 100 no

interestRate = .06

interestRate = .10

Pseudocode
Fundamentals of Algorithmds

IF amount < 100 interestRate = .06 ELSE Interest Rate = .10 ENDIF

The Looping Structure


In flowcharting one of the more confusing things is to separate selection from looping.
This is because each structure use the diamond as their control symbol. In pseudocode we avoid this by using specific keywords to designate looping

WHILE/ENDWHILE REPEAT/UNTIL
Fundamentals of Algorithmds

Tips on Writing Good Pseudo Code


Use indention for improved clarity Do not put code in pseudo code make your pseudo code language independent Dont write pseudo code for yourself write it in an unambiguous fashion so that anyone with a reasonable knowledge can understand and implement it

Be consistent
Prefer formulas over English language descriptions
Fundamentals of Algorithmds

Das könnte Ihnen auch gefallen