Movatterモバイル変換


[0]ホーム

URL:


Uploaded byVictorMorcillo1
PPT, PDF111 views

Programming algorithms and flowchart.ppt

The document provides an overview of programming concepts, algorithms, and flowcharts, explaining how programming involves writing instructions in a computer-understandable format using programming languages. It discusses the steps in problem-solving, the role of pseudocode, and different control structures like sequence, decision, and repetition within programming. Additionally, it illustrates how to represent algorithms and their corresponding flowcharts through various examples, emphasizing the importance of matching the flowchart with the algorithm's logic.

Download to read offline
PROGRAMMING,ALGORITHMS ANDFLOWCHARTS
What is Programming? Series of instructions to a computer toaccomplish a task Instructions must be written in a way thecomputer can understand Programming languages are used to writeprograms
ALGORITHMS AND FLOWCHARTS A typical programming task can be divided intotwo phases: Problem solving phase produce an ordered sequence of steps that describesolution of problem this sequence of steps is called an algorithm Implementation phase implement the program in some programminglanguage
Devise an algorithm for cooking a sausage on a barbecue
Steps in Problem Solving First produce a general algorithm. Refine the algorithm successively to get step bystep detailed algorithm that is very close to acomputer language. Pseudocode is an artificial and informallanguage that helps programmers developalgorithms. Pseudocode is very similar toeveryday English.
Pseudocode & Algorithm Example 1: Write an algorithm todetermine a student’s final grade andindicate whether it is passing or failing.The final grade is calculated as theaverage of four marks. Start with a general algorithm.
General AlgorithmPseudocode: Input a set of 4 marks Calculate their average by summing and dividingby 4 if average is below 50Print “FAIL”elsePrint “PASS”
Detailed AlgorithmStep 1: Input M1,M2,M3,M4Step 2: GRADE  (M1+M2+M3+M4)/4Step 3: if (GRADE < 50) thenPrint “FAIL”elsePrint “PASS”endif
Task: add two numbers Pseudocode:StartGet two numbersAdd themPrint the answerEnd
Next Step - The Flowchart A graphical representation of the sequence ofoperations in an information system or program.Information system flowcharts show how data flows fromsource documents through the computer to finaldistribution to users. Program flowcharts show thesequence of instructions in a single program orsubroutine. Different symbols are used to draw eachtype of flowchart. The sequence of the flowchart and the algorithm MUSTmatch.
The FlowchartA Flowchartshows logic of an algorithmemphasizes individual steps and theirinterconnectionse.g. control flow from one action to the next
Flowchart SymbolsBasicOvalParallelogramRectangleDiamondHybridName Symbol Use in FlowchartDenotes the beginning or end of the programDenotes an input operationDenotes an output operationDenotes a decision (or branch) to be made.The program should continue along one oftwo 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 programModuleDenotes a self-contained section of theprogram
ExamplePRINT“PASS”Step 1: Input M1,M2,M3,M4Step 2: GRADE  (M1+M2+M3+M4)/4Step 3: if (GRADE <50) thenPrint “FAIL”elsePrint “PASS”endifSTARTInputM1,M2,M3,M4GRADE(M1+M2+M3+M4)/4ISGRADE<50PRINT“FAIL”STOPYN
Control StructuresRepresent the flow of logic through the programme.There are four main control structures:• Sequence• Decision – incorporating if-then-else• Repetition• Case
Sequence Structure• a series of actions are performed in sequenceSTARTDisplay message“How manyhours did youwork?”Read HoursDisplay message“How much doyou get paid perhour?”Read Pay RateMultiply Hoursby Pay Rate.Store result inGross Pay.Display GrossPayENDThis is the flowchart for a program whichcalculates an employee’s gross pay.
Example 1 Write an algorithm and draw a flowchart toconvert the length in feet to centimetres.Pseudocode: Input the length in feet (Lft) Calculate the length in cm (Lcm) bymultiplying LFT with 30 Print length in cm (LCM)
ExampleAlgorithm Step 1: Input Lft Step 2: Lcm  Lft x 30 Step 3: Print LcmSTARTInputLftLcm  Lft x 30STOPFlowchartPrintLcm
Example 2Write an algorithm and draw a flowchart thatwill read the two sides of a rectangle andcalculate its area.Pseudocode Input the width (W) and Length (L) of a rectangle Calculate the area (A) by multiplying L with W Print A
Example 2Algorithm Step 1: Input W,L Step 2: A  L x W Step 3: Print ASTARTInputW, LA  L x WSTOPPrintA
DECISION STRUCTURES One of two possible actions is taken, dependingon a condition.Decision StructureA new symbol, the diamond, indicates a yes/no question.
Decision Structures Sometimes only one choice is necessaryYESNO
Example 1 Pseudocode:StartGet year bornCalculate agePrint ageIf age > 50 print OLDEnd
 Flowchart Start Get year born Calculate age Print age If age > 50 print OLD EndGet yrCalc agePrint ageAge>50OLDYNStartEnd
Decision Structure Sometimes two choices are offered. If the answer to thequestion is yes, the flow follows one path. If the answeris no, the flow follows another pathYESNO
Decision Structure In the flowchart segment below, the question “is x < y?”is asked. If the answer is no, then process A isperformed. If the answer is yes, then process B isperformed.YESNOx < yProcess BProcess A
IF–THEN–ELSE STRUCTURE The structure is as followsIf condition thentrue alternativeelsefalse alternative
IF–THEN–ELSE STRUCTURE The algorithm for the flowchart is asfollows:If A>B thenprint Aelseprint BisA>BPrintAPrintBN Y
Example 1A ticket seller is issuing show tickets at the gate. When the patrons arrive,he asks how old each one is. It they are under 12, they pay half price. If theyare 12 or over, they pay full price.AlgorithmGet ageAge < 12?If Age < 12ThenPay half priceElsePay full price
FlowchartYESNOBeginInput ageAge < 12Half priceFull priceEnd
Example 2 Write an algorithm that reads two values, determines thelargest value and prints the largest value with anidentifying message.ALGORITHMStep 1: Input VALUE1, VALUE2Step 2: if (VALUE1 > VALUE2) thenMAX  VALUE1elseMAX  VALUE2endifStep 3: Print “The largest value is”, MAX
Example 2MAX  VALUE2STOPN YSTARTInputVALUE1,VALUE2MAX  VALUE1isVALUE1>VALUE2PrintMAX
Example 3 Write the algorithm and draw the flowchartfor the following: Enter two numbers, x and y. If x is lessthan y, square x to give the result a,otherwise, add x + y to give the result a.
YESNOx < yCalculate aas x times 2.Calculate aas x plus y.AlgorithmInput xInput yx < y?If x <yThena = x^Elsea = x+y
NESTED IFS One of the alternatives within an IF–THEN–ELSE statementmay involve further IF–THEN–ELSEstatement
Repetition StructureRepetition (Iteration) Structure A repetition structure represents part of the programthat repeats. This type of structure is commonlyknown as a loop.
Repetition Structure Notice the use of the diamond symbol. A loop tests acondition, and if the condition exists, it performs anaction. Then it tests the condition again. If thecondition still exists, the action is repeated. Thiscontinues until the condition no longer exists.
Repetition Structure In the flowchart segment, the question “is x < y?”is asked. If the answer is yes, then Process A isperformed. The question “is x < y?” is askedagain. Process A is repeated as long as x is lessthan y. When x is no longer less than y, therepetition stops and the structure is exited.x < y Process AYES
x < y Add 1 to xYESSo this might look like…When would this loop exit?
The action performed by a repetition structure must eventually cause the loop toterminate. Otherwise, an infinite loop is created.In this flowchart segment, x is never changed. Once the loop starts, it will neverend.QUESTION: How can this flowchart be modified so it is no longer an infiniteloop?Out of Control!x < y Display xYES
This type of structure is known as a pre-testrepetition structure. The condition is testedBEFORE any actions are performed.Pre-test ( Before) Loopx < y? Display xAdd 1 to xYES
Post-test (After) LoopThis flowchart segment shows apost-test repetition structure.The condition is tested AFTERthe actions are performed.A post-test repetition structurealways performs its actions atleast once.Display xAdd 1 to xYESx < y
Case Structure One of several possible actions is taken, depending onthe contents of a variable. Used for MORE THAN TWO decisions
 The structure below indicates actions toperform depending on the value inyears_employed.CASEyears_employed1 2 3 Otherbonus = 100 bonus = 200 bonus = 400 bonus = 800
CASEyears_employed1 2 3 Otherbonus = 100 bonus = 200 bonus = 400 bonus = 800If years_employed = 1,bonus is set to 100If years_employed = 2,bonus is set to 200If years_employed = 3,bonus is set to 400If years_employed isany other value, bonusis set to 800
Case AlgorithmInput a GradeCase based on GradeCase =100Report “Perfect Score” (or suitable command eg Grade = Perfect)Case > 89Report “Grade = A”Case > 79Report “Grade = B”Case > 69Report “Grade = C”Case > 59Report “Grade = D”Default (or Else)Report “Grade = F”End CaseDraw the Flowchart for the above example
CASEgrade>89 >79 >69 > 59Grade =A Grade = B Grade = C Grade = DFlowchartGrade = Perfect Grade = F100 other
Construct the algorithm and the flowchart for thefollowing procedure:An egg packing business needs to devise aprocess to sort eggs for delivery to supermarkets.If the eggs weigh 50 grams, they are Class Aeggs. If they weigh 60 grams, they are Class Beggs. If they weigh 70 grams, they are Class Ceggs. If they weigh more than 70 grams, they areClass D eggs.
Input a WeightCase based on WeightCase =50Class = ACase =60Class = BCase = 70Class = CCase > 70Class = DORDefault/ Else Class = DEnd CaseAlgorithmCASEweight50 60 70 > 70Class =A Class = B Class = C Class = DFlowchart
Modules (stepwise refinement)A program module is a part of a program thatmakes sense on its own, just like a paragraphin an essay should make sense on its own. Inlarge programs, such as those used inindustry, programs are developed asseparate modules and then put together.The process of representing modules inflowcharts is known as stepwise refinement.You will look at this more closely when youstart programming.
•The position of the modulesymbol indicates the point themodule is executed.•A separate flowchart can beconstructed for the module.STARTENDRead Input.Call calc_payfunction.Display results.STARTDisplay message“How manyhours did youwork?”Read HoursDisplay message“How much doyou get paid perhour?”Read Pay RateMultiply Hoursby Pay Rate.Store result inGross Pay.Display GrossPayEND
A simpler example… could look likeCASEweight50 60 70 > 70Class =A Class = B Class = C Class =DInput weightCalculate classDisplay class
A complete program exampleWhen you use stepwise refinement, the complete, refined flowchart is drawn first.Then the modules are named and drawn in order.This program lists the AFL team name and points total for all teams that have a full-forward from the AFL competitionwho has kicked at least 10 goals.
StartupHeadings
MainLoopAFLGoals >= 10CheckgoalsCheck posCheck goalsCheck conf
FinishAlthough this procedure is listed as a module in the opening flow chart, it’sunsuitable. Why?

Recommended

PPT
Decision making and branching
PPTX
Looping statements in C
PPTX
3.looping(iteration statements)
PPTX
Design Procedure for an Integrator
PPT
8086-instruction-set-ppt
PPTX
Multi level inheritence
PPTX
Rules of Karnaugh Map
PPTX
V.o.r ppt
 
PPTX
C formatted and unformatted input and output constructs
PPT
Rotate instructions
PPTX
DMA and DMA controller
PPT
Unions in c
PPTX
File in C language
PPTX
Virtual function in C++ Pure Virtual Function
PPT
Power amplifiers
PPTX
Voltage Amplifier
PPTX
SUMMING AMPLIFIER
 
PDF
Schering bridge Experiment
PPT
Driving large capacitive loads
PDF
Time domain specifications of second order system
PPTX
Flipflop
PDF
Operational Amplifiers
PPTX
Deadbeat Response Design _8th lecture
PPTX
Aircraft navigation system
PPTX
SINGULAR POINT IN NON-LINEAR SYSTEM
PPTX
PPTX
Algorithms and Flowcharts
PPT
01 Algorithms And Flowcharts.ppt

More Related Content

PPT
Decision making and branching
PPTX
Looping statements in C
PPTX
3.looping(iteration statements)
PPTX
Design Procedure for an Integrator
PPT
8086-instruction-set-ppt
PPTX
Multi level inheritence
PPTX
Rules of Karnaugh Map
PPTX
V.o.r ppt
 
Decision making and branching
Looping statements in C
3.looping(iteration statements)
Design Procedure for an Integrator
8086-instruction-set-ppt
Multi level inheritence
Rules of Karnaugh Map
V.o.r ppt
 

What's hot

PPTX
C formatted and unformatted input and output constructs
PPT
Rotate instructions
PPTX
DMA and DMA controller
PPT
Unions in c
PPTX
File in C language
PPTX
Virtual function in C++ Pure Virtual Function
PPT
Power amplifiers
PPTX
Voltage Amplifier
PPTX
SUMMING AMPLIFIER
 
PDF
Schering bridge Experiment
PPT
Driving large capacitive loads
PDF
Time domain specifications of second order system
PPTX
Flipflop
PDF
Operational Amplifiers
PPTX
Deadbeat Response Design _8th lecture
PPTX
Aircraft navigation system
PPTX
SINGULAR POINT IN NON-LINEAR SYSTEM
PPTX
C formatted and unformatted input and output constructs
Rotate instructions
DMA and DMA controller
Unions in c
File in C language
Virtual function in C++ Pure Virtual Function
Power amplifiers
Voltage Amplifier
SUMMING AMPLIFIER
 
Schering bridge Experiment
Driving large capacitive loads
Time domain specifications of second order system
Flipflop
Operational Amplifiers
Deadbeat Response Design _8th lecture
Aircraft navigation system
SINGULAR POINT IN NON-LINEAR SYSTEM

Similar to Programming algorithms and flowchart.ppt

PPTX
Algorithms and Flowcharts
PPT
01 Algorithms And Flowcharts.ppt
PPT
Algorithms and Flowchart.ppt
PPTX
Algorithms and flowcharts
PPTX
Draw the flowchart of the above algorithm.pptx
PPTX
Algorithmsandflowcharts1
PPT
256958.ppt
PDF
ALGORITHM PPT GUIDE.pdf
PDF
Flowcharts. Algorithms and pseudo codepdf
PPTX
Algorithms-Flowcharts for programming fundamental
PPT
Algorithmsandflowcharts1
PDF
ALGORITHMS AND FLOWCHARTS
PDF
Algorithms and flowcharts
PPT
Algorithmsandflowcharts1
PPT
Algorithms and flowcharts ppt (seminar presentation)..
PPT
Best Techniques To Design Programs - Program Designing Techniques
 
PPTX
Psuedocode1, algorithm1, Flowchart1.pptx
PPT
Proble, Solving & Automation
PPT
Program design techniques
PPT
UNIT- 3-FOC.ppt
Algorithms and Flowcharts
01 Algorithms And Flowcharts.ppt
Algorithms and Flowchart.ppt
Algorithms and flowcharts
Draw the flowchart of the above algorithm.pptx
Algorithmsandflowcharts1
256958.ppt
ALGORITHM PPT GUIDE.pdf
Flowcharts. Algorithms and pseudo codepdf
Algorithms-Flowcharts for programming fundamental
Algorithmsandflowcharts1
ALGORITHMS AND FLOWCHARTS
Algorithms and flowcharts
Algorithmsandflowcharts1
Algorithms and flowcharts ppt (seminar presentation)..
Best Techniques To Design Programs - Program Designing Techniques
 
Psuedocode1, algorithm1, Flowchart1.pptx
Proble, Solving & Automation
Program design techniques
UNIT- 3-FOC.ppt

Recently uploaded

PPTX
business economics unit 3 production dr kanchan (1).pptx
PDF
Get to know your EEG and MEG data - artifacts, segmenting, preprocessing
PDF
Unit4DC_TransportLayer &NetworkLayer.pdf
PPTX
How to Create Event Booth in Odoo 18 Event
PPTX
GROWTH AND DEVELOPMENT..............pptx
PPTX
Targeted Drug Delivery System – Liposomes, Nanoparticles, Niosomes & Monoclon...
PPTX
ANKYLOSING SPONDYLITIS OR BAMBOO SPINE.pptx
PPTX
28 October 2025 - Andreas Schleicher presents at the OECD Webinar Insights on...
PDF
Projects_for_Ministries,_Departments_&_Agencies2123341679.pdf
PDF
BED 105-B- Orientation - BEd. First Year - 2025
PPTX
Banking Company Accounts in Corporate Accounting .pptx
PDF
FA Term 2 Reiki Yoga All Student Workshop 22
PDF
20th C Landscape architects - Noguchi & Burle marx.pdf
PPTX
Prometheans Gyanotsav quiz - the mixed bag
PPTX
Nasopulmonary drug delivery system Pradip Sontakke
PPTX
Developmental stage of Binocular vision.pptx
PDF
Selection in Genetics and Plant Breeding | Complete Concept Explained 🌾
PDF
Plant Domestication | Complete Concept Explained BREEDING PLANT DOMESTICATION
PDF
Major Evolutionary Patterns in Crop Plants: Implications for Breeding and Div...
PDF
Heat-Transfer-in-Nature.pdf/7th class new ncert/by k sandeep swamy/samyans ed...
business economics unit 3 production dr kanchan (1).pptx
Get to know your EEG and MEG data - artifacts, segmenting, preprocessing
Unit4DC_TransportLayer &NetworkLayer.pdf
How to Create Event Booth in Odoo 18 Event
GROWTH AND DEVELOPMENT..............pptx
Targeted Drug Delivery System – Liposomes, Nanoparticles, Niosomes & Monoclon...
ANKYLOSING SPONDYLITIS OR BAMBOO SPINE.pptx
28 October 2025 - Andreas Schleicher presents at the OECD Webinar Insights on...
Projects_for_Ministries,_Departments_&_Agencies2123341679.pdf
BED 105-B- Orientation - BEd. First Year - 2025
Banking Company Accounts in Corporate Accounting .pptx
FA Term 2 Reiki Yoga All Student Workshop 22
20th C Landscape architects - Noguchi & Burle marx.pdf
Prometheans Gyanotsav quiz - the mixed bag
Nasopulmonary drug delivery system Pradip Sontakke
Developmental stage of Binocular vision.pptx
Selection in Genetics and Plant Breeding | Complete Concept Explained 🌾
Plant Domestication | Complete Concept Explained BREEDING PLANT DOMESTICATION
Major Evolutionary Patterns in Crop Plants: Implications for Breeding and Div...
Heat-Transfer-in-Nature.pdf/7th class new ncert/by k sandeep swamy/samyans ed...

Programming algorithms and flowchart.ppt

  • 1.
  • 2.
    What is Programming?Series of instructions to a computer toaccomplish a task Instructions must be written in a way thecomputer can understand Programming languages are used to writeprograms
  • 3.
    ALGORITHMS AND FLOWCHARTSA typical programming task can be divided intotwo phases: Problem solving phase produce an ordered sequence of steps that describesolution of problem this sequence of steps is called an algorithm Implementation phase implement the program in some programminglanguage
  • 4.
    Devise an algorithmfor cooking a sausage on a barbecue
  • 5.
    Steps in ProblemSolving First produce a general algorithm. Refine the algorithm successively to get step bystep detailed algorithm that is very close to acomputer language. Pseudocode is an artificial and informallanguage that helps programmers developalgorithms. Pseudocode is very similar toeveryday English.
  • 6.
    Pseudocode & AlgorithmExample 1: Write an algorithm todetermine a student’s final grade andindicate whether it is passing or failing.The final grade is calculated as theaverage of four marks. Start with a general algorithm.
  • 7.
    General AlgorithmPseudocode: Inputa set of 4 marks Calculate their average by summing and dividingby 4 if average is below 50Print “FAIL”elsePrint “PASS”
  • 8.
    Detailed AlgorithmStep 1:Input M1,M2,M3,M4Step 2: GRADE  (M1+M2+M3+M4)/4Step 3: if (GRADE < 50) thenPrint “FAIL”elsePrint “PASS”endif
  • 9.
    Task: add twonumbers Pseudocode:StartGet two numbersAdd themPrint the answerEnd
  • 10.
    Next Step -The Flowchart A graphical representation of the sequence ofoperations in an information system or program.Information system flowcharts show how data flows fromsource documents through the computer to finaldistribution to users. Program flowcharts show thesequence of instructions in a single program orsubroutine. Different symbols are used to draw eachtype of flowchart. The sequence of the flowchart and the algorithm MUSTmatch.
  • 11.
    The FlowchartA Flowchartshowslogic of an algorithmemphasizes individual steps and theirinterconnectionse.g. control flow from one action to the next
  • 12.
    Flowchart SymbolsBasicOvalParallelogramRectangleDiamondHybridName SymbolUse in FlowchartDenotes the beginning or end of the programDenotes an input operationDenotes an output operationDenotes a decision (or branch) to be made.The program should continue along one oftwo 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 programModuleDenotes a self-contained section of theprogram
  • 13.
    ExamplePRINT“PASS”Step 1: InputM1,M2,M3,M4Step 2: GRADE  (M1+M2+M3+M4)/4Step 3: if (GRADE <50) thenPrint “FAIL”elsePrint “PASS”endifSTARTInputM1,M2,M3,M4GRADE(M1+M2+M3+M4)/4ISGRADE<50PRINT“FAIL”STOPYN
  • 14.
    Control StructuresRepresent theflow of logic through the programme.There are four main control structures:• Sequence• Decision – incorporating if-then-else• Repetition• Case
  • 15.
    Sequence Structure• aseries of actions are performed in sequenceSTARTDisplay message“How manyhours did youwork?”Read HoursDisplay message“How much doyou get paid perhour?”Read Pay RateMultiply Hoursby Pay Rate.Store result inGross Pay.Display GrossPayENDThis is the flowchart for a program whichcalculates an employee’s gross pay.
  • 16.
    Example 1 Writean algorithm and draw a flowchart toconvert the length in feet to centimetres.Pseudocode: Input the length in feet (Lft) Calculate the length in cm (Lcm) bymultiplying LFT with 30 Print length in cm (LCM)
  • 17.
    ExampleAlgorithm Step 1:Input Lft Step 2: Lcm  Lft x 30 Step 3: Print LcmSTARTInputLftLcm  Lft x 30STOPFlowchartPrintLcm
  • 18.
    Example 2Write analgorithm and draw a flowchart thatwill read the two sides of a rectangle andcalculate its area.Pseudocode Input the width (W) and Length (L) of a rectangle Calculate the area (A) by multiplying L with W Print A
  • 19.
    Example 2Algorithm Step1: Input W,L Step 2: A  L x W Step 3: Print ASTARTInputW, LA  L x WSTOPPrintA
  • 20.
    DECISION STRUCTURES Oneof two possible actions is taken, dependingon a condition.Decision StructureA new symbol, the diamond, indicates a yes/no question.
  • 21.
    Decision Structures Sometimesonly one choice is necessaryYESNO
  • 22.
    Example 1 Pseudocode:StartGetyear bornCalculate agePrint ageIf age > 50 print OLDEnd
  • 23.
     Flowchart StartGet year born Calculate age Print age If age > 50 print OLD EndGet yrCalc agePrint ageAge>50OLDYNStartEnd
  • 24.
    Decision Structure Sometimestwo choices are offered. If the answer to thequestion is yes, the flow follows one path. If the answeris no, the flow follows another pathYESNO
  • 25.
    Decision Structure Inthe flowchart segment below, the question “is x < y?”is asked. If the answer is no, then process A isperformed. If the answer is yes, then process B isperformed.YESNOx < yProcess BProcess A
  • 26.
    IF–THEN–ELSE STRUCTURE Thestructure is as followsIf condition thentrue alternativeelsefalse alternative
  • 27.
    IF–THEN–ELSE STRUCTURE Thealgorithm for the flowchart is asfollows:If A>B thenprint Aelseprint BisA>BPrintAPrintBN Y
  • 28.
    Example 1A ticketseller is issuing show tickets at the gate. When the patrons arrive,he asks how old each one is. It they are under 12, they pay half price. If theyare 12 or over, they pay full price.AlgorithmGet ageAge < 12?If Age < 12ThenPay half priceElsePay full price
  • 29.
    FlowchartYESNOBeginInput ageAge <12Half priceFull priceEnd
  • 30.
    Example 2 Writean algorithm that reads two values, determines thelargest value and prints the largest value with anidentifying message.ALGORITHMStep 1: Input VALUE1, VALUE2Step 2: if (VALUE1 > VALUE2) thenMAX  VALUE1elseMAX  VALUE2endifStep 3: Print “The largest value is”, MAX
  • 31.
    Example 2MAX VALUE2STOPN YSTARTInputVALUE1,VALUE2MAX  VALUE1isVALUE1>VALUE2PrintMAX
  • 32.
    Example 3 Writethe algorithm and draw the flowchartfor the following: Enter two numbers, x and y. If x is lessthan y, square x to give the result a,otherwise, add x + y to give the result a.
  • 33.
    YESNOx < yCalculateaas x times 2.Calculate aas x plus y.AlgorithmInput xInput yx < y?If x <yThena = x^Elsea = x+y
  • 34.
    NESTED IFS Oneof the alternatives within an IF–THEN–ELSE statementmay involve further IF–THEN–ELSEstatement
  • 36.
    Repetition StructureRepetition (Iteration)Structure A repetition structure represents part of the programthat repeats. This type of structure is commonlyknown as a loop.
  • 37.
    Repetition Structure Noticethe use of the diamond symbol. A loop tests acondition, and if the condition exists, it performs anaction. Then it tests the condition again. If thecondition still exists, the action is repeated. Thiscontinues until the condition no longer exists.
  • 38.
    Repetition Structure Inthe flowchart segment, the question “is x < y?”is asked. If the answer is yes, then Process A isperformed. The question “is x < y?” is askedagain. Process A is repeated as long as x is lessthan y. When x is no longer less than y, therepetition stops and the structure is exited.x < y Process AYES
  • 39.
    x < yAdd 1 to xYESSo this might look like…When would this loop exit?
  • 40.
    The action performedby a repetition structure must eventually cause the loop toterminate. Otherwise, an infinite loop is created.In this flowchart segment, x is never changed. Once the loop starts, it will neverend.QUESTION: How can this flowchart be modified so it is no longer an infiniteloop?Out of Control!x < y Display xYES
  • 41.
    This type ofstructure is known as a pre-testrepetition structure. The condition is testedBEFORE any actions are performed.Pre-test ( Before) Loopx < y? Display xAdd 1 to xYES
  • 42.
    Post-test (After) LoopThisflowchart segment shows apost-test repetition structure.The condition is tested AFTERthe actions are performed.A post-test repetition structurealways performs its actions atleast once.Display xAdd 1 to xYESx < y
  • 43.
    Case Structure Oneof several possible actions is taken, depending onthe contents of a variable. Used for MORE THAN TWO decisions
  • 44.
     The structurebelow indicates actions toperform depending on the value inyears_employed.CASEyears_employed1 2 3 Otherbonus = 100 bonus = 200 bonus = 400 bonus = 800
  • 45.
    CASEyears_employed1 2 3Otherbonus = 100 bonus = 200 bonus = 400 bonus = 800If years_employed = 1,bonus is set to 100If years_employed = 2,bonus is set to 200If years_employed = 3,bonus is set to 400If years_employed isany other value, bonusis set to 800
  • 46.
    Case AlgorithmInput aGradeCase based on GradeCase =100Report “Perfect Score” (or suitable command eg Grade = Perfect)Case > 89Report “Grade = A”Case > 79Report “Grade = B”Case > 69Report “Grade = C”Case > 59Report “Grade = D”Default (or Else)Report “Grade = F”End CaseDraw the Flowchart for the above example
  • 47.
    CASEgrade>89 >79 >69> 59Grade =A Grade = B Grade = C Grade = DFlowchartGrade = Perfect Grade = F100 other
  • 48.
    Construct the algorithmand the flowchart for thefollowing procedure:An egg packing business needs to devise aprocess to sort eggs for delivery to supermarkets.If the eggs weigh 50 grams, they are Class Aeggs. If they weigh 60 grams, they are Class Beggs. If they weigh 70 grams, they are Class Ceggs. If they weigh more than 70 grams, they areClass D eggs.
  • 49.
    Input a WeightCasebased on WeightCase =50Class = ACase =60Class = BCase = 70Class = CCase > 70Class = DORDefault/ Else Class = DEnd CaseAlgorithmCASEweight50 60 70 > 70Class =A Class = B Class = C Class = DFlowchart
  • 50.
    Modules (stepwise refinement)Aprogram module is a part of a program thatmakes sense on its own, just like a paragraphin an essay should make sense on its own. Inlarge programs, such as those used inindustry, programs are developed asseparate modules and then put together.The process of representing modules inflowcharts is known as stepwise refinement.You will look at this more closely when youstart programming.
  • 51.
    •The position ofthe modulesymbol indicates the point themodule is executed.•A separate flowchart can beconstructed for the module.STARTENDRead Input.Call calc_payfunction.Display results.STARTDisplay message“How manyhours did youwork?”Read HoursDisplay message“How much doyou get paid perhour?”Read Pay RateMultiply Hoursby Pay Rate.Store result inGross Pay.Display GrossPayEND
  • 52.
    A simpler example…could look likeCASEweight50 60 70 > 70Class =A Class = B Class = C Class =DInput weightCalculate classDisplay class
  • 53.
    A complete programexampleWhen you use stepwise refinement, the complete, refined flowchart is drawn first.Then the modules are named and drawn in order.This program lists the AFL team name and points total for all teams that have a full-forward from the AFL competitionwho has kicked at least 10 goals.
  • 54.
  • 55.
  • 56.
    FinishAlthough this procedureis listed as a module in the opening flow chart, it’sunsuitable. Why?

[8]ページ先頭

©2009-2025 Movatter.jp