algorithm programming

34
Programming In C 1 Objectives of these slide Objectives of these slide s: s: introduce C using a few e introduce C using a few e xamples xamples Algorithms and Flow Charts Programming In C Programming In C MCA-102(N2) MCA-102(N2)

Upload: rajeshkripal3945

Post on 15-Nov-2014

106 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Algorithm Programming

Programming In C 1

Objectives of these slides: Objectives of these slides: introduce C using a few exam introduce C using a few exam

plesples

Algorithms and Flow Charts

Programming In CProgramming In CMCA-102(N2)MCA-102(N2)

Page 2: Algorithm Programming

2Programming In C

What is an algorithm?What is an algorithm?

… … a well-defined procedure that allows an a well-defined procedure that allows an agent to solve a problem. agent to solve a problem.

Note: often the agent is a computer or a robot…Note: often the agent is a computer or a robot…

Example algorithmsExample algorithms Cooking a dish Cooking a dish Making a peanut-butter jelly sandwichMaking a peanut-butter jelly sandwich Shampooing hairShampooing hair Programming a VCR Programming a VCR Making a pieMaking a pie

Page 3: Algorithm Programming

3Programming In C

ExampleExample

Is this an algorithm? Is this an algorithm?

Step 1: Wet hairStep 1: Wet hair Step 2: LatherStep 2: Lather Step 3: RinseStep 3: Rinse Step 4: RepeatStep 4: Repeat

Would you manage to wash your hair with Would you manage to wash your hair with this algorithm? How about a robot? Why this algorithm? How about a robot? Why (not)?(not)?

Page 4: Algorithm Programming

4Programming In C

Algorithms Algorithms

An algorithm must:An algorithm must:

1. Be well-ordered and unambigous1. Be well-ordered and unambigous

2. Each operation must be effectively 2. Each operation must be effectively computablecomputable

3. Terminate.3. Terminate.

Page 5: Algorithm Programming

5Programming In C

ExampleExample

Problem: Find and print the 100th prime numberProblem: Find and print the 100th prime number A prime number is a whole number not evenly divisible A prime number is a whole number not evenly divisible

by any other number other than 1 and itselfby any other number other than 1 and itself

Algorithm (?):Algorithm (?):1. Generate a list of all primi numbers L1, L2, L3,1. Generate a list of all primi numbers L1, L2, L3,……2. Sort the list into ascending order2. Sort the list into ascending order3. Print out the 100th element in this list3. Print out the 100th element in this list

Is this an algorithm?Is this an algorithm?

Page 6: Algorithm Programming

6Programming In C

Algorithm for Programming Algorithm for Programming a VCRa VCR

Step 1: If the clock and calendar are not correctly set, then Step 1: If the clock and calendar are not correctly set, then go to page 9 of the instruction manual and follow the go to page 9 of the instruction manual and follow the instructions before proceedinginstructions before proceeding

Step 2: Place a blank tape into the VCR tape slotStep 2: Place a blank tape into the VCR tape slot Step 3: Repeat steps 4 through 7 for each program that you Step 3: Repeat steps 4 through 7 for each program that you

wish to record, up to a maximum of 10 showswish to record, up to a maximum of 10 shows Step 4: Enter the channel number that you wish to record, Step 4: Enter the channel number that you wish to record,

and press the button labeled CHANand press the button labeled CHAN Step 5: Enter the start time and press TIME-STARTStep 5: Enter the start time and press TIME-START Step 6: Enter the end time and press END-TIMEStep 6: Enter the end time and press END-TIME Step 7: This completes the programming of one show. If you Step 7: This completes the programming of one show. If you

do not wish to program anything else press END-PROGdo not wish to program anything else press END-PROG Step 8: Press te button labeles TIMER. Your VCR is ready to Step 8: Press te button labeles TIMER. Your VCR is ready to

record.record.

Page 7: Algorithm Programming

7Programming In C

Types of OperationsTypes of Operations Basic operationsBasic operations

Wet hairWet hair RinseRinse Turn on VCRTurn on VCR

Conditional operationsConditional operations If batter is too dry add waterIf batter is too dry add water

Repeat/looping operationsRepeat/looping operations Repeat step 1 and 2 three timesRepeat step 1 and 2 three times Repeat steps 2,3,4,…10 until batter Repeat steps 2,3,4,…10 until batter

becomes soft.becomes soft.

Page 8: Algorithm Programming

8Programming In C

AlgorithmAlgorithm

How to come up with an algorithm? How to come up with an algorithm? That is, how to discover an algorithm That is, how to discover an algorithm

underlying a problem? underlying a problem? Problem solvingProblem solving

How to represent an algorithm? How to represent an algorithm? In English??In English?? In a programming language??In a programming language??

Page 9: Algorithm Programming

9Programming In C

ExampleExample Problem: Given two positive integers, compute their Problem: Given two positive integers, compute their

greatest common divisorgreatest common divisor

Euclid’s algorithm: Euclid’s algorithm: Step 1: Get two positive integer values from the Step 1: Get two positive integer values from the

useruser Step 2: Assign M and N the value of the larger and Step 2: Assign M and N the value of the larger and

smaller of the two input values, respectivelysmaller of the two input values, respectively Step 3: Divide M by N, and call the remainder RStep 3: Divide M by N, and call the remainder R Step 4: If R is not 0, then assign M the value of N, Step 4: If R is not 0, then assign M the value of N,

assign te value of R, and return to step 2; otherwise, assign te value of R, and return to step 2; otherwise, the greatest common divisor is the value currently the greatest common divisor is the value currently assigned to Nassigned to N

Page 10: Algorithm Programming

10Programming In C

Coming up with Coming up with algorithms..algorithms..

How do people think????How do people think????

Puzzle: Puzzle: Before A, B, C and D ran a race they made the Before A, B, C and D ran a race they made the

following predictions: following predictions: A predicted that B would winA predicted that B would win B predicted that D would be lastB predicted that D would be last C predicted that A would be thirdC predicted that A would be third D predicted that A’s prediction would be D predicted that A’s prediction would be

correct.correct. Only one of these predictions was true, and this Only one of these predictions was true, and this

was the prediction made by the winner. was the prediction made by the winner. In what order did A, B, C, D finish the race?In what order did A, B, C, D finish the race?

Page 11: Algorithm Programming

11Programming In C

ExampleExample Problem: Adding two n-digit numbersProblem: Adding two n-digit numbers

7597831 +7597831 + 12875251287525--------------------------------------

88853568885356

How would you write an algorithm to How would you write an algorithm to solve this problem? Assume the basic solve this problem? Assume the basic operation is adding one-digit numbers. operation is adding one-digit numbers.

Page 12: Algorithm Programming

12Programming In C

Expressing algorithmsExpressing algorithms Is natural language good? Is natural language good?

For daily life, yes…but for CS is lacks For daily life, yes…but for CS is lacks structure and would be hard to followstructure and would be hard to follow

Too rich, ambiguous, depends on contextToo rich, ambiguous, depends on context

How about a programming language? How about a programming language? Good, but not when we try to solve a Good, but not when we try to solve a

problem..we want to think at an abstract problem..we want to think at an abstract levellevel

It shifts the emphasis from how to solve the It shifts the emphasis from how to solve the problem to tedious details of syntax and problem to tedious details of syntax and grammar.grammar.

Page 13: Algorithm Programming

13Programming In C

PseudocodePseudocode Pseudocode = English but looks like programmingPseudocode = English but looks like programming

Good compromise Good compromise Simple, readable, no rules, don’t worry about Simple, readable, no rules, don’t worry about

punctuation. punctuation.

Lets you think at an abstract level about the Lets you think at an abstract level about the problem. problem.

Contains only instructions that have a well-defined Contains only instructions that have a well-defined structure and resemble programming languagesstructure and resemble programming languages

Page 14: Algorithm Programming

14Programming In C

PseudocodePseudocode Basic (primitive) operationsBasic (primitive) operations

Read the input from userRead the input from user Print the output to the userPrint the output to the user Cary out basic arithmetical computationsCary out basic arithmetical computations

Conditional operationsConditional operations Execute an operation if a condition is trueExecute an operation if a condition is true

Repeat operationsRepeat operations Execute a block of operation multiple times Execute a block of operation multiple times

until a certain condition is metuntil a certain condition is met

Page 15: Algorithm Programming

15Programming In C

VariablesVariablesVariableVariable

A named memory location that can store a valueA named memory location that can store a value Think of it as a box into which you can store a Think of it as a box into which you can store a

value, and from which you can retrieve a valuevalue, and from which you can retrieve a value

Examples:Examples:

Example of operationsExample of operations Set the value of i to 3Set the value of i to 3 Set the value of M to i*3 + 12Set the value of M to i*3 + 12 Set the value of i to i+10Set the value of i to i+10

i M

Page 16: Algorithm Programming

16Programming In C

A model for visualizing an algorithmA model for visualizing an algorithm

Algorithm

Variables

Operations

An algorithm consists of operations that involve variables

Page 17: Algorithm Programming

17Programming In C

Primitive operationsPrimitive operations Get input from userGet input from user

Get the value of x from userGet the value of x from user

Assign values to variables using basic arithmetic Assign values to variables using basic arithmetic operationsoperations

Set the value of x to 3Set the value of x to 3 Set the value of y to x/10Set the value of y to x/10 Set the value of z to x +25Set the value of z to x +25

Print output to userPrint output to user Print the value of y, z to the userPrint the value of y, z to the user

Page 18: Algorithm Programming

18Programming In C

Example 1Example 1

Problem: For any three numbers input by the user, Problem: For any three numbers input by the user, compute their sum and average and output compute their sum and average and output them them

Example of algorithm in pseudocode:Example of algorithm in pseudocode:

Variables: a,b,c, sum, avgVariables: a,b,c, sum, avg Get the values of a, b, c from userGet the values of a, b, c from user Set avg to (a+b+c)/3 Set avg to (a+b+c)/3 Set sum to (a+b+c)Set sum to (a+b+c) Print sum and avgPrint sum and avg

Page 19: Algorithm Programming

19Programming In C

Example 2Example 2

Problem: Given any value of radius from the user, Problem: Given any value of radius from the user, compute and print the circumference of a circle compute and print the circumference of a circle with that radiuswith that radius

Algorithm in pseudocode:Algorithm in pseudocode:

variables: r, cvariables: r, c

1. Get the value of r from user1. Get the value of r from user

2. Set c to 2 * pi * r2. Set c to 2 * pi * r

3. Print “The circumference of your circle is “ c3. Print “The circumference of your circle is “ c

Page 20: Algorithm Programming

20Programming In C

What is a flowchart?What is a flowchart?

Logic diagram to describe each step Logic diagram to describe each step that the program must perform to that the program must perform to arrive at the solution.arrive at the solution.

A popular logic tool used for A popular logic tool used for showing an algorithm in graphics showing an algorithm in graphics form.form.

Page 21: Algorithm Programming

21Programming In C

Continue flowchartContinue flowchart

Programmer prepares flowchart Programmer prepares flowchart before coding.before coding.

Most common flowchart symbols Most common flowchart symbols are:are:

Direction of logic flow

Beginning/end of a task

Input/outputoperation

Logic comparison operations. Have one entry and two exit points

data manipulation operations e.g arithmetic

Page 22: Algorithm Programming

22Programming In C

Purpose of Flowcharting:Purpose of Flowcharting:

An aid in developing the logic of a An aid in developing the logic of a program.program.

Verification that all possible Verification that all possible conditions have been considered in a conditions have been considered in a program.program.

Provides means of communication Provides means of communication with others about the program.with others about the program.

A guide in coding the program.A guide in coding the program. Documentation for the program.Documentation for the program.

Page 23: Algorithm Programming

23Programming In C

ExampleExample Olive Peach has a fruit stall in the local Olive Peach has a fruit stall in the local

marketmarket She wants a program which will calculate a She wants a program which will calculate a

customer’s bill, given the cost per kilo of the customer’s bill, given the cost per kilo of the fruit purchased and the number of kilos fruit purchased and the number of kilos boughtbought

The program should then print out the billThe program should then print out the bill This problem will only deal with one purchase This problem will only deal with one purchase

per customerper customer Input will be from the keyboard; output will Input will be from the keyboard; output will

be to the screen using appropriate headers.be to the screen using appropriate headers.

Page 24: Algorithm Programming

24Programming In C

Solution (1)Solution (1)

AnalyseAnalyse identify the problemidentify the problem

Calculate the cost of fruit, given cost per Calculate the cost of fruit, given cost per kilo and the number of kilos boughtkilo and the number of kilos bought

Design a solution (Do this on paper)Design a solution (Do this on paper) A typical purchase might be bananas:A typical purchase might be bananas:

Cost per kilo – 90cCost per kilo – 90c Kilos bought - 2Kilos bought - 2 Total cost of purchase = 90 * 2 = €1.80cTotal cost of purchase = 90 * 2 = €1.80c

Page 25: Algorithm Programming

25Programming In C

Solution (2)Solution (2) Design the output to be displayedDesign the output to be displayed

Olive Peach – Fruit MerchantOlive Peach – Fruit MerchantThe Old MarketThe Old MarketCost per kilo = $0.90cCost per kilo = $0.90cKilos bought = 2Kilos bought = 2Total cost = $1.80cTotal cost = $1.80c

Sketch the interface design (form)Sketch the interface design (form) Implement your solution in VBImplement your solution in VB Debug and testDebug and test Document each stageDocument each stage

Page 26: Algorithm Programming

26Programming In C

Olive Peach: Flow Olive Peach: Flow DiagramDiagram

Start

Get cost per kilo

Get weight

Calculate cost

Display bill

Page 27: Algorithm Programming

27Programming In C

Desk CheckingDesk Checking

The process of testing the flowchart with The process of testing the flowchart with different data as input, and checking the different data as input, and checking the output.output.

The test data should include nonstandard The test data should include nonstandard data as well as typical data.data as well as typical data.

Page 28: Algorithm Programming

28Programming In C

What is a Pseudocode?What is a Pseudocode?

A program design technique that A program design technique that uses English words.uses English words.

Has no formal syntactical rules.Has no formal syntactical rules.

Page 29: Algorithm Programming

29Programming In C

Olive Peach: Pseudo Olive Peach: Pseudo Code (1)Code (1)

StepsSteps 1 Get cost per kilo1 Get cost per kilo 2 Get weight (in kilos)2 Get weight (in kilos) 3 Calculate total cost3 Calculate total cost 4 Display the bill4 Display the bill

Page 30: Algorithm Programming

30Programming In C

Olive Peach: Pseudo Olive Peach: Pseudo Code (2)Code (2)

StepsSteps 1 Get cost per kilo1 Get cost per kilo

1.1 Prompt user to enter cost1.1 Prompt user to enter cost 1.2 Read in the cost from the keyboard1.2 Read in the cost from the keyboard

2 Get weight2 Get weight 2.1 Prompt user to enter weight2.1 Prompt user to enter weight 2.2 Read in the weight from the keyboard2.2 Read in the weight from the keyboard

3 Calculate total cost3 Calculate total cost 3.1 Set total cost equal to weight multiplied by cost3.1 Set total cost equal to weight multiplied by cost

4 Display the bill4 Display the bill 4.1 Display bill headings 4.1 Display bill headings 4.2 Display bill details (the cost, weight and total cost)4.2 Display bill details (the cost, weight and total cost)

Page 31: Algorithm Programming

31Programming In C

What is a Hierarchy What is a Hierarchy Chart?Chart?

Shows the overall program’s Shows the overall program’s structure.structure.

Describes what each part, or Describes what each part, or module, of the program does.module, of the program does.

Also how each module relates to Also how each module relates to other modules in the program.other modules in the program.

Page 32: Algorithm Programming

32Programming In C

Example of Hierarchy Example of Hierarchy Chart:Chart:

Olive Peach program

Get costper kilo

Calculate total cost

Get weight Display bill

Page 33: Algorithm Programming

33Programming In C

More than 1 iteMore than 1 itemm: Flow : Flow ChartChart

Start

Initialize item=1total cost = 0

Are there more items

Get next cost per kilo

Calculate cost

Add cost to total cost

Yes

No

Get next weight

Increment item

Page 34: Algorithm Programming

34Programming In C

More than 1 More than 1 item :item :PseudocodePseudocode

Determine the Determine the total cost if more than total cost if more than one itemone item::Do while there are moreDo while there are more items items Get the next Get the next cost per kilocost per kilo

Get Get tthe next weighthe next weightCalculate tCalculate thhe coste costadd it to total costadd it to total cost

Increment Increment itemsitemsLoopLoopDisplayDisplay total cost total cost