Algorithm And Flowchart - Suman Ojha

2y ago
10 Views
2 Downloads
263.99 KB
31 Pages
Last View : 18d ago
Last Download : 3m ago
Upload by : Brenna Zink
Transcription

Algorithm and Flowchart204112 Structured Programming1

Programming MethodologyProblem solving Problem statement and analysis Develop a high-level algorithm Detail out a low-level algorithmCoding Choose a programming language Code the program using the selected algorithm Test the program and correct the errors204112 Structured Programming2

AlgorithmDefinition – Solution to a computer programmingproblem.Algorithm can be written in 2 different ways Pseudo-code – English-like steps thatdescribes the solution Flowcharts – Picture with specific blocksdetailing out the logical flow of the solution204112 Structured Programming3

Flowchart Building BlocksCONTROL FLOWTERMINAL POINT - Start / EndPROCESS - Initializing, Calculation .INPUT / OUTPUT - Keyboard, Display .DECISIONCONNECTOR - used for big diagram across pagesPRINTOUT STORAGE - Read or Write from CDs, Disks, TapesSUB-ROUTINE204112 Structured Programming4

Example 1Problem StatementStartSwitch on the TVSwitch on the UBCWatch a movie at homeAlgorithm1. Switch on the TV andUBC sets2. Change to the requiredmovie channel3. Sit down and watch themovieChange to themovie channelSit downWatch movieEnd204112 Structured Programming5

StartExample 2Go to the ATMProblem StatementInsert your card intothe ATM machineWithdraw cash from ATMAlgorithm1. Go to the ATM2. Insert your card into themachine3. Press in your code4. Choose “Withdraw” andenter Amount required5. Take the cash, slip andcard.204112 Structured ProgrammingPress in your codeChoose WithdrawEnter the amountTake the cashTake the slipTake the cardEnd6

StartExample 3Problem StatementCalculate the interest of abank deposit. You are toread the amount, yearsand interest rate from thekeyboard and print theinterest amount.Algorithm1.2.3.4.Read AmountRead YearsRead RateSet Interest as Amount *Rate * Years / 1005. Print Interest204112 Structured ProgrammingInput AmountInput YearsInput RateCompute Interest Amount * Years * Rate/ 100Output InterestEnd7

Example 3 – Input/Output SamplesInputsOutputsAmount 5000Years 2Rate 2Interest 200Amount 1000Years 1.5Rate 2.5Interest 37.50204112 Structured Programming8

Example 4StartProblem StatementInput SignalPrint what to do whendriving to a traffic signalYesAlgorithm1.2.Read traffic signalIf signal is GREEN thenSignal GREEN ?Action - GONoAction - STOPSet Action as GOElseSet Action as STOP3.Output ActionPrint ActionEnd204112 Structured Programming9

Example 4 – Input/Output SamplesInputsOutputsSignal GREENAction GOSignal REDAction STOPSignal YELLOWAction STOPCheck what happens ifSignal BLUEAction 204112 Structured Programming10

Example 5StartProblem StatementInput NRead a number from the keyboard.Check and output if a givennumber N is ODD or EVENAlgorithm1.2.3.Remainder - N modulo 2YesRead NSet Remainder as N modulo 2If Remainder is equal to 0 thenRemainder 0 ?Answer - EVENNoAnswer - ODDSet Answer as EVENElseOutput AnswerSet Answer as ODD4.Print AnswerEnd204112 Structured Programming11

Example 5 – Input/Output SamplesInputsOutputsN 5Answer ODDN 8Answer EVENN 0Answer EVENN -1Answer ODD204112 Structured Programming12

StartExample 6Input GenderNoProblem StatementPrint Title for a person (Either Mr. orMiss. or Mrs.). You are to read thegender (and status if needed).Gender Male ?Input StatusYesStatus Married ?Title - Mr.Algorithm1.2.Read GenderIf Gender is MALE thenTitle is Mr.ElseRead StatusIf Status is MARRIED thenTitle is Mrs.ElseTitle is Miss.3.Print TitleYesTitle - Mrs.NoTitle - MissOutput TitleEnd204112 Structured Programming13

Example 6 – Input/Output SamplesInputsOutputsGender MaleTitle Mr.Gender FemaleStatus MarriedTitle Mrs.Gender FemaleStatus SingleTitle Miss.Check what happens ifGender BoyStatus IntelligentTitle 204112 Structured Programming14

Example 7StartInitialize X - 0Problem StatementIncrement X by 1Print 1 to 20Print XAlgorithm1.2.3.4.Initialize X as 0Increment X by 1Print XIf X is less than 20 thengo back to Step 2Yes X 20NoEnd204112 Structured Programming15

StartExample 8Problem StatementGiven computer time is stored in 24hours format, you are to print thetime in AM/PM formatExtractHOURSExtract MINUTESNoHOURS 0 ?YesAlgorithm1.2.3.Retrieve computer timeRetrieve computer timeExtract Hours and MinutesIf Hours is equal to 0 thenYesOutput 12Print 124.5.6.Print „:‟Print MinutesIf Hours is less than 12 thenPrint AMOutput HOURSNoOutput (Hours - 12)Output ":"ElseIf Hours is between 1 and 12thenPrint HoursElsePrint Hours – 121 HOURS 12Output MINUTESYesNoHOURS 12Output AMOutput PMElsePrint PMEnd204112 Structured Programming16

Example 8 – Input/Output SamplesInputsOutputsComputer time 8:30Printed time – 8:30 AMComputer time 20:30Printed time – 8:30 PMComputer time 0:15Printed time – 12:15 AMComputer time 12:15Printed time – 12:15 PM204112 Structured Programming17

StartExample 9Input MONTHYESMONTH 2 ?NOProblem StatementRead the Month (and Year, if needed)and print the number of days inthat monthAlgorithm1.Read MONTH2.If MONTH is equal to 2 thenRead YEARIf YEAR is a leap year thenSet DAYS as 29ElseSet DAYS as 28ElseInput YEARSet LEAP - YEAR modulo 4NOLEAP 0 ?YESNOYESSet DAYS - 30Set DAYS - 28MONTH 4 orMONTH 6 orMONTH 9 orMONTH 11?Set DAYS - 31Set DAYS - 29If MONTH is either 4 or 6 or 9 or 11thenSet DAYS as 30ElseSet DAYS as 313.Print DAYS204112 Structured ProgrammingOutput DAYSEnd18

Example 9 – Input/Output SamplesInputsOutputsMonth 2Year 2004Days 29Month 2Year 2005Month 10Days 28Month 4Days 30Check what happens ifMonth -1Days 204112 Structured ProgrammingDays 3119

Example 10Problem StatementPrepare sandwichesHigh-level Algorithm1. Go to the nearest supermarket2. Pick the groceries you need3. Pay at the cashier4. Bring the groceries home5. Prepare the sandwiches204112 Structured ProgrammingLow-level Algorithm1.1 Take the car keys and wallet from the counter1.2 Drive the car to the supermarket1.3 Park the car1.4 Take the lift to the supermarket floor2.1 Take an empty cart and walk around the floor2.2 Put the needed groceries into the cart2.3 Take the cart to the cashier3.1 Give the credit card to the cashier3.2 Sign on the credit card slip4.1Take the cart with the plastic bags to the car4.2 Put the plastic bags to the car4.3 Drive the car home4.4 Remove the plastic bags from the car5.1 Cut the bread into half5.2 Prepare the bacon and salad5.3 Put the ingredients between 2 slices of bread20

Example 11Problem StatementMake an urgent call to yourfriend from the airportHigh-level Algorithm1. Go to a public booth2. Dial your friend‟s number3. Give the message to yourfriend204112 Structured ProgrammingLow-level Algorithm1.1 Walk to the next phone booth1.2 If phone booth is not working, then repeatfrom step 1.12.1 Retrieve the number from pocket diary2.2 Put some coins into the slot.2.3 Dial the number2.4 If the line is busy, hang up, then takeback the coins and repeat from step 2.23.1 If your friend can come to the phone, thentalk to your friend.3.2 If your friend cannot come to the phone,then leave a message for your friend.3.2 Hang up the phone.3.4 Retrieve any coins not used.21

StartExample 11Walk to next phone boothPhone working ?NOYESRetrieve Number from Pocket DiaryPut some coins into the slotDial the numberLine is busy ?YESNOYESFriend found ?Talk to friendNOLeave messageHang up the phoneRetrieve the unused coins204112 Structured ProgrammingEnd22

Example 12Problem StatementAutomatically return change for apurchase of N baht when givena 20 baht note. Check that N isbetween 1 and 20.High-level Algorithm1. Read and Validate N2. Calculate Change3. Decide how many 10 bahtcoins, 5 baht coins and 1 bahtcoins to returnLow-level Algorithm1.1 Read N1.2 If NOT (1 N 20) thenPrint Error MessageGo back to Step 1.12.1 Initialize CHANGE as 202.2 Deduct N from CHANGE3.1 If CHANGE is less than 10 thenNumber of 10 baht coin is 0.ElseNumber of 10 baht coin is 1.Deduct 10 from CHANGE3.2 If CHANGE is less than 5 thenWhat happens if customer can pay by anykinds of banknotes: 1000, 500, 100, 20, and10. and any kinds of coins: 10, 5, 2, and 1.That means N is not be fixed.204112 Structured ProgrammingNumber of 5 baht coin is 0.ElseNumber of 5 baht coin is 1.Deduct 5 from CHANGE3.3 Number of 1 baht coin is CHANGE23

StartExample 12Input NOutput ErrorCheck what happens if N 20Check what happens if N 0Check what happens if N 21N 1 and N 20NOYESSet CHANGE - 20 - NYESCHANGE 10 ?NOSet COIN10 - 1Set CHANGE - CHANGE - 10Set COIN10 - 0YESCHANGE 5 ?NOSet COIN05 - 1SET CHANGE - CHANGE - 5SET COIN05 - 0Set COIN01 - CHANGE204112 Structured ProgrammingEnd24

Example 12 – Input/Output SamplesInputsOutputsN 17Number of 10 B coin – 0Number of 5 B coin – 0Number of 1 B coin – 3N 6Number of 10 B coin – 1Number of 5 B coin – 0Number of 1 B coin – 4N 13Number of 10 B coin – 0Number of 5 B coin – 1Number of 1 B coin – 2Check what happens if N 20Check what happens if N 0Check what happens if N 21204112 Structured Programming25

Example 13Problem StatementFind the average of a givenlist of numbersHigh-level Algorithm1. Find the SUM of thegiven numbers2. Find the COUNT of thegiven numbers3. AVERAGE is SUM †COUNT204112 Structured ProgrammingLow-level Algorithm1. Initialize SUM as 0 and COUNT as 02. If there are no more numbersremaining to be processed, then goto step 7.3. Set ITEM as next number in the list4. Add ITEM to SUM5. Increment COUNT by 16. Go back to step 27. If COUNT is equal to 0, thenAVERAGE is “undefined”ElseAVERAGE is SUM † COUNT26

StartExample 13Set SUM - 0Set COUNT - 0NOAny more unprocessed numbers ?YESSet ITEM - Next number in listSet SUM - SUM ITEMSet COUNT - COUNT 1YESCOUNT 0 ?NOSet AVERAGE SUM / COUNTOutput "Undefined" Error204112 Structured ProgrammingOutput AVERAGEEnd27

Example 13 – Input/Output SamplesInputsOutputsList 20, 2, 5, -3Average 6List 2, 5, -3, -8, -1Average -1List 2, 7, 5, 3, 6Average 4.60List 4Average 4List Average “undefined”204112 Structured Programming28

Example 14Problem StatementGiven a 2-D polygon with N sides (and N vertices). Find the smallestrectangular box required to cover the polygon completelyAlgorithm1.Initialize MINX, MINY, MAXX, MAXY using the 1st Vertex2.Retrieve the next unevaluated vertex (X, Y)3.If X MINX, then set MINX as X4.If X MAXX, then set MAXX as X5.If Y MINY, then set MINY as Y6.If Y MAXY, then set MAXY as Y7.If all vertices have not been evaluated then go back to step 28.Set LENGTH as MAXX – MINX9.Set HEIGHT as MAXY – MINY204112 Structured Programming29

StartGet the 1st Vertex (X,Y)Example 14Set MINX - XSet MAXX - XSet MINY - YSet MAXY - YGet the next Vertex (X,Y)X MINXYESASet MINX - XNOBX MAXXYESSet MAXX - XNOSet LENGTH - MAXX - MINXSet HEIGHT - MAXY - MINYY MINYYESSet MINY - YNOEndY MAXYYESSet MAXY - YNOB204112 Structured ProgrammingNOAny unevaluated vertex left ?YESA30

Example 14 – Input/Output SamplesInputsOutputs4 sides (2,2) (5,3) (3,5) (6,2)Length 4Height 33 sides (1,2) (5,3) (8, -2)Length 7Height 55 sides (2,5) (7,1) (3,2) (-3, -5)(4,1)Length 10Height 10204112 Structured Programming31

COUNT Low-level Algorithm 1. Initialize SUM as 0 and COUNT as 0 2. If there are no more numbers remaining to be processed, then go to step 7. 3. Set ITEM as next number in the list 4. Add ITEM to SUM 5. Increment COUNT by 1 6. Go back to step 2 7. If COUNT is equal to 0, then AVERAGE is “undefined” Else AVERAGE is SUM †COUNT

Related Documents:

20. Write an algorithm and flowchart to find the given no is positive or not. 21. Write an algorithm and flowchart to swap the two nos. 22. Write an algorithm and flowchart to convert temperature in Celsius 23. Write an algorithm and flowchart take digit from user and display 24. Write an algorithm and flowchart enter year from user and check. 25.

Flowchart di bedakan menjadi 5 jenis flowchart, antara lain system flowchart, document flowchart, schematic flowchart, program flowchart, . menggunakan symbol-simbol bagan alir sistem, juga menggunakan gambar-gambar computer dan peralatan lainnya yang digunakan. Maksud penggunaa gambar-gambar ini adalah untuk memudahkan .

Keep in mind that a flowchart may not need to include all the possible symbols. For example, the wait symbol ( ) may not be needed if the flowchart is not related to waiting times. Improving the layout of a flowchart Create a complex flowchart Analyzing the Detailed Flowchart to Identify Problem Areas

OA flowchart is the graphical or pictorial representation of an algorithm with the help of different symbols, shapes and arrows in order to demonstrate a process or a program. With algorithms, we can easily understand a program. The main purpose of a flowchart is to analyze different processes. Several standard graphics are applied in a flowchart:

Flowchart I If Thorax Extension/Rotation SMCD exists lumbar spine is normal. If not consider this a Weight-bearing Spine or Shoulder Girdle Rotation SMCD - DN Go to Hip Rotation Flowchart 1 Treat Pain - Go to Hip Rotation Flowchart I FP or DP Treat Pain - Go to Hip Rotation Flowchart I MULTI

The Fair Culture Flowchart can be used for any employee involved in a safety incident. The Fair Culture Flowchart is specifically for use following a safety accident or incident. The flowchart should be applied to the immediate cause identified by the investigation where it is an unsafe act and any other unsafe acts identified by the investigation.

The flowchart package Flowchart Shapes for TikZ Adrian P. Robson† 19 March 2015 1 Introduction rts. Theyarebasedon

America’s Problem-Solving Courts: The Criminal Costs of Treatment and the Case for Reform CYNTHIA HUJAR ORR President, NACDL San Antonio, TX JOHN WESLEY HALL Immediate Past President, NACDL Little Rock, AR NORMAN L. R EIMER Executive Director, NACDL Washington, DC EDWARD A. M ALLETT President, FCJ Houston, TX KYLE O’D OWD Associate Executive Director For Policy, NACDL Washington, DC .