2 What is Programming?Series of instructions to a computer to accomplish a taskInstructions must be written in a way the computer can understandProgramming languages are used to write programs
3 ALGORITHMS AND FLOWCHARTS A typical programming task can be divided into two phases:Problem solving phaseproduce an ordered sequence of steps that describe solution of problemthis sequence of steps is called an algorithmImplementation phaseimplement the program in some programming language
4 Devise an algorithm for cooking a sausage on a barbecue
5 Steps in Problem Solving First produce a general algorithm.Refine the algorithm successively to get step by step detailed algorithm that is very close to a computer language.Pseudocode is an artificial and informal language that helps programmers develop algorithms. Pseudocode is very similar to everyday English.
6 Pseudocode & Algorithm Example 1: Write an algorithm to determine a student’s final grade and indicate whether it is passing or failing. The final grade is calculated as the average of four marks.Start with a general algorithm.
7 General Algorithm Pseudocode: Input a set of 4 marks Calculate their average by summing and dividing by 4if average is below 50Print “FAIL”elsePrint “PASS”
9 Task: add two numbers Pseudocode: Start Get two numbers Add them Print the answerEnd
10 Next Step - The Flowchart A graphical representation of the sequence of operations in an information system or program. Information system flowcharts show how data flows from source documents through the computer to final distribution to users. Program flowcharts show the sequence of instructions in a single program or subroutine. Different symbols are used to draw each type of flowchart.The sequence of the flowchart and the algorithm MUST match.
11 The Flowchart A Flowchart shows logic of an algorithm emphasizes individual steps and their interconnectionse.g. control flow from one action to the next
12 Flowchart Symbols Basic Denotes a self-contained section of the programModule
14 Control Structures Represent the flow of logic through the programme. There are four main control structures:SequenceDecision – incorporating if-then-elseRepetitionCase
15 Sequence Structure a series of actions are performed in sequence STARTDisplay message “How many hours did you work?”Read HoursDisplay message “How much do you get paid per hour?”Read Pay RateMultiply Hours by Pay Rate. Store result in Gross Pay.Display Gross PayENDa series of actions are performed in sequenceThis is the flowchart for a program which calculates an employee’s gross pay.
16 Example 1Write an algorithm and draw a flowchart to convert the length in feet to centimetres.Pseudocode:Input the length in feet (Lft)Calculate the length in cm (Lcm) by multiplying LFT with 30Print length in cm (LCM)
17 Example Algorithm Step 1: Input Lft Step 2: Lcm Lft x 30 FlowchartAlgorithmStep 1: Input LftStep 2: Lcm Lft x 30Step 3: Print LcmSTARTInputLftLcm Lft x 30STOPPrintLcm
18 Example 2Write an algorithm and draw a flowchart that will read the two sides of a rectangle and calculate its area.PseudocodeInput the width (W) and Length (L) of a rectangleCalculate the area (A) by multiplying L with WPrint A
19 Example 2 Algorithm Step 1: Input W,L Step 2: A L x W Step 3: Print ASTARTInputW, LA L x WSTOPPrintA
20 DECISION STRUCTURES Decision Structure One of two possible actions is taken, depending on a condition.A new symbol, the diamond, indicates a yes/no question.
21 Decision StructuresSometimes only one choice is necessaryYESNO
22 Example 1 Pseudocode: Start Get year born Calculate age Print age If age > 50 print OLDEnd
23 Flowchart Start Get year born Calculate age Print age Get yrFlowchartStartGet year bornCalculate agePrint ageIf age > 50 print OLDEndCalc agePrint ageYAge>50OLDNEnd
24 Decision StructureSometimes two choices are offered. If the answer to the question is yes, the flow follows one path. If the answer is no, the flow follows another pathYESNO
25 Decision StructureIn the flowchart segment below, the question “is x < y?” is asked. If the answer is no, then process A is performed. If the answer is yes, then process B is performed.YESNOx < yProcess BProcess A
26 IF–THEN–ELSE STRUCTURE The structure is as followsIf condition thentrue alternativeelsefalse alternative
27 IF–THEN–ELSE STRUCTURE The algorithm for the flowchart is as follows:If A>B thenprint Aelseprint BisA>BPrint APrint BNY
28 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 they are 12 or over, they pay full price.AlgorithmGet ageAge < 12?If Age < 12ThenPay half priceElsePay full price
30 Example 2Write an algorithm that reads two values, determines the largest value and prints the largest value with an identifying message.ALGORITHMStep 1: Input VALUE1, VALUE2Step 2: if (VALUE1 > VALUE2) thenMAX VALUE1elseMAX VALUE2endifStep 3: Print “The largest value is”, MAX
31 Example 2 MAX VALUE2 STOP N Y START Input VALUE1,VALUE2 MAX VALUE1 isVALUE1>VALUE2PrintMAX
32 Example 3Write the algorithm and draw the flowchart for the following:Enter two numbers, x and y. If x is less than y, square x to give the result a, otherwise, add x + y to give the result a.
33 YES NO x < y Algorithm Input x Input y x < y? If x <y Then a = x^Elsea = x+yYESNOx < yCalculate a as x times 2.Calculate a as x plus y.
34 NESTED IFS One of the alternatives within an IF–THEN–ELSE statement may involve further IF–THEN–ELSE statement
36 Repetition (Iteration) Structure Repetition StructureRepetition (Iteration) StructureA repetition structure represents part of the program that repeats. This type of structure is commonly known as a loop.
37 Repetition StructureNotice the use of the diamond symbol. A loop tests a condition, and if the condition exists, it performs an action. Then it tests the condition again. If the condition still exists, the action is repeated. This continues until the condition no longer exists.
38 Repetition StructureIn the flowchart segment, the question “is x < y?” is asked. If the answer is yes, then Process A is performed. The question “is x < y?” is asked again. Process A is repeated as long as x is less than y. When x is no longer less than y, the repetition stops and the structure is exited.x < yProcess AYES
39 So this might look like… x < yAdd 1 to xYESWhen would this loop exit?
40 Out of Control! YES x < y Display x The action performed by a repetition structure must eventually cause the loop to terminate. Otherwise, an infinite loop is created.In this flowchart segment, x is never changed. Once the loop starts, it will never end.QUESTION: How can this flowchart be modified so it is no longer an infinite loop?x < yDisplay xYES
41 Pre-test ( Before) Loop This type of structure is known as a pre-test repetition structure. The condition is tested BEFORE any actions are performed.x < y?Display xAdd 1 to xYES
42 Post-test (After) Loop Display xAdd 1 to xYESx < yThis flowchart segment shows a post-test repetition structure.The condition is tested AFTER the actions are performed.A post-test repetition structure always performs its actions at least once.
43 Case StructureOne of several possible actions is taken, depending on the contents of a variable.Used for MORE THAN TWO decisions
44 The structure below indicates actions to perform depending on the value in years_employed. CASE years_employed123Otherbonus = 100bonus = 200bonus = 400bonus = 800
45 1 2 3 Other If years_employed = 2, bonus is set to 200 CASE years_employed123Otherbonus = 100bonus = 200bonus = 400bonus = 800If years_employed = 1, bonus is set to 100If years_employed is any other value, bonus is set to 800
46 Draw the Flowchart for the above example Case AlgorithmInput a Grade Case based on Grade Case =100 Report “Perfect Score” (or suitable command eg Grade = Perfect) Case > 89 Report “Grade = A” Case > 79 Report “Grade = B” Case > 69 Report “Grade = C” Case > 59 Report “Grade = D” Default (or Else) Report “Grade = F” End CaseDraw the Flowchart for the above example
47 >89 >79 >69 > 59 100 other Flowchart CASE grade Grade =A Grade = BGrade = CGrade = D100otherGrade = PerfectGrade = F
48 Construct the algorithm and the flowchart for the following procedure: An egg packing business needs to devise a process to sort eggs for delivery to supermarkets. If the eggs weigh 50 grams, they are Class A eggs. If they weigh 60 grams, they are Class B eggs. If they weigh 70 grams, they are Class C eggs. If they weigh more than 70 grams, they are Class D eggs.
49 50 60 70 > 70 Algorithm Flowchart Input a Weight Case based on Weight Case =50 Class = A Case =60 Class = B Case = 70 Class = C Case > 70 Class = D OR Default/ Else Class = D End CaseCASE weight506070> 70Class =AClass = BClass = CClass = D
50 Modules (stepwise refinement) A program module is a part of a program that makes sense on its own, just like a paragraph in an essay should make sense on its own. In large programs, such as those used in industry, programs are developed as separate modules and then put together.The process of representing modules in flowcharts is known as stepwise refinement. You will look at this more closely when you start programming.
51 A separate flowchart can be constructed for the module. STARTDisplay message “How many hours did you work?”Read HoursDisplay message “How much do you get paid per hour?”Read Pay RateMultiply Hours by Pay Rate. Store result in Gross Pay.Display Gross PayENDSTARTENDRead Input.Call calc_pay function.Display results.The position of the module symbol indicates the point the module is executed.A separate flowchart can be constructed for the module.
52 A simpler example… could look like CASE weight506070> 70Class =AClass = BClass = CClass = DInput weightCalculate classDisplay class
53 A complete program example When 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 competition who has kicked at least 10 goals.