1 / 53

Programming Methods (PM)

Programming Methods (PM). Chapter 2 VARIABLES, CONTROL STRUCTURES AND CALCULATIONS. Chapter OBJECTIVES:. Understand the importance of order of precedence Describe control structures Use calculations to construct computer programs Describe the different variable types and naming conventions.

eporter
Download Presentation

Programming Methods (PM)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programming Methods (PM) Chapter 2VARIABLES, CONTROL STRUCTURES AND CALCULATIONS

  2. Chapter OBJECTIVES: • Understand the importance of order of precedence • Describe control structures • Use calculations to construct computer programs • Describe the different variable types and naming conventions

  3. Chapter CONTENTS: • Variables and simple data types • Order of precedence • Control structures • Sequence • Selection • Loops • Pseudocode • Diagrams and charting

  4. Chapter 2Variables, Control Structures and Calculations PART 1Introduction

  5. Example: • “You can use the mouse to select a menu” • For i = 1 to 10 Print “Message” Next i 1.1 Introduction • Every programming language has rules which must be followed in the same way as a spoken language • grammar, order of words • The English language consists of words which must be used in grammatical way to have meaning.

  6. 1.2 Introduction (cont.) • The building blocks are reserved words • IF • FOR NEXT • DO WHILE • REPEAT UNTIL • IF THEN ELSE • Each Program will have a unique set of reserved words

  7. 1.3 Definitions of Key Terms  Syntax • The rules defining the legal sequences of symbolic elements in a language, but say nothing about the meaning of those constructs  Language Constructs • A syntactic structure or set of instructions in a language to express a particular class or operations.

  8. Example: • IF – THEN – ELSE • DO – WHILE - LOOP  Keyword • A symbol in programming language that has a special meaning for the compiler or interpreter. Example: • PRINT, “”, := 1.4 Definitions of Key Terms Reserved Words • Words that has specific roles in the context in which it occurs, which cannot be used for other purposes.

  9. 1.5 Definitions of Key Terms  Pseudocode/Pseudolanguage • Used to provide an outline description of the specification for the software module • Contain a natural language of expressions embedded in syntactic structures taken from programming language • IF…THEN…ELSE • REPEAT..UNTIL • Not intended to be executed by a computer, must be interpreted by people.

  10. NOTE: • Diagrams (flowcharts) are use to represent algorithms • The diagrams shown illustrates how to compute the sum of three numbers • Process is performed on the data and the results are returned to the user or retained for use at a latter stage 1.6 Solution in the Form of a Diagram

  11. Chapter 2Variables, Control Structures and Calculations PART 2Variables Types and Names

  12. 2.1 What is a Variable? • They are used to store data in the computer’s memory (RAM) • The address in the memory where the data is stored • The actual data stored which can change during the execution of the program • That name of the identifier or variable

  13. VISUAL BASIC Program: (High Level) Private Sub cmdComputeSum() Dim sum as Integer sum = Val(txtNumber1.Text) + Val(txtNumber2.Text)+ Val(txtNumber3.Text) Print sum End Sub 2.2 Example: Compute Sum BASIC Program: (High Level) Begin ACCEPT number1,number2,number3 Sum:=number1+number2+number3 PRINT sum End Program

  14. 2.3 What is an Identifier? • A string of characters required to identify (or name) some element of a program. It maybe a: • variable • data structure • a procedure • statement • higher level unit • They are usually written in text that provides a meaningful name such as: • average_student • AverageStudent • rate_per_hour • RatePerHour

  15. 2.4 What is an Assignment Statement? • A fundamental statement for all programming languages that assigns new value to a variable.

  16. Example: • Data objects, variables, functions, procedures • nodes, stations, processes (data communication network) • Files, directories, devices (OS) 2.3 What is a Name? • A notation for indicating an entity in a program or system • Generally a name must be simple identifier, usually a textual string • Names are converted to addresses by a process name lookup

  17. 2.4 Variable Types Integer • whole numbers (e.g. 1, 678, 345) Real or Float • fractional numbers (e.g. 3.24) Character • letter (e.g. a, f, x, c, 4) String • names (e.g. Dr. H. Kelly, Sg. 745) Boolean • TRUE or FALSE (0 or 1)

  18. 2.4 Variable Types (cont.) • English postal codes contain lettersanda space, which a computer treats as a blank character • The computer would use this this data as a string because it contains a blank character • Numbers are only declared as integeror real if the are to be used in calculations • Many programming languages insists on variables definition at the beginning of the program Good practice to: • Identify the variables used and the types in the pseudocode • Describe any printed or displayed output, rather than just printing number

  19. PSEUDOCODE: Use variables : number1,number2,number3, sum OF TYPE integer DISPLAY “Enter three numbers” ACCEPT number1,number2,number3 sum:=number1+number2+number3 PRINT “The sum is:”sum End Program NOTE: • It is a good practice to identify the variables used and the types in the pseudocode • It is also a good practice to describe any printed or displayed output • The data stored under the variable is controlled by the program 2.5 Example of Pseudocode

  20. 2.6 Definitions of Key Terms  Constant • A quantity or data item whose values des not change • rate_hour = 20 • deductions = 120 • gas_liter = .50 • A value is determined by its denotation (literal)  Literal • A word or symbol in a program that stands for itself and rather than as a name for something else. • Numbers are literals • If other symbols are used as literals, it is necessary to use some form of quoting mechanism to distinguish them from variables

  21. Chapter 2Variables, Control Structures and Calculations PART 3Order of Precedence

  22. 3.1 The Order of Precedence • Computer languages provide a range of operators for arithmetic (arithmetic operators) • + meaning add • - meaning subtract • * meaning multiply • / meaning divide • The order in which a calculation is evaluated is very important since the end result can differ according to which operation is given precedence

  23. SOLUTION 1: • Add the 4 to the 3 and then multiply the result by 2 • (4+3=7) (7*2=14) SOLUTION 2: • Multiply the 3 by the 2 and then add 4 to the result • (3*2=6) (6+4=10) NOTE: • Different methods resulted in two different results. • Having rules of order of precedence of the arithmetic operations avoids ambiguity. • The way expressions are worked out are very similar to the rules in mathematics. 3.2 The Order of Precedence SCENARIO: a:= 4 + 3*2 could be worked out in two different orders

  24. NOTE: • The correct answer for the expression a:= 4 + 3*2 is 10 • 4 + (3*2) = 10 3.3 The Order of Precedence • Do operations in brackets first • Then evaluate any exponentiation • finding the cube of a number • work out 6 to the power of 4 • Then any division or multiplication operation • Lastly, addition and subtraction BODMAS • Bracket • Of • Division • Multiplication • Addition • Subtraction

  25. Chapter 2Variables, Control Structures and Calculations PART 4Control Structure

  26. 4.1 Control Structure • The main types of instructions are used in programming • sequence • selection • loops • Control structure – definition • A syntactic form in a language to express flow of control • Common control structures are • IF.. THEN.. ELSE • WHILE..DO • REPEAT.. UNTIL • CASE

  27. 4.2 Control Structure - SEQUENCE • The easiest type of control structure • Very important that the instructions are in the right order • The computer will obey (perform) the instructions implicitly in the order in which they are written

  28. 4.3 Control Structure - SELECTION • Many occasions where a program is required to include a range of alternative actions EXAMPLE: Division by Zero Checking • Imagine a program in which one number (a constant) is divided by another (a variable) • The contents of the variable can change throughout the program and it is possible that the variable contains a zero • As it is not possible to divide by zero, the calculation should not be performed on this data • Therefore this condition has to be tested for • This can be illustrated in the form of a flowchart

  29. NOTE: • Used extensively by programmers before the advent of pseudocode • Still a useful tool to help programmers work out the logic of the sequence of instructions needed, particularly where conditions occur • note that the results of the test are placed on the lines exiting from the decision box • best to write the condition in a form where the two choices are yes or no (i.e. TRUE or FALSE), as this matches the IF … THEN … ELSE statement NOTE: Checking for dividing by zero 4.4 Selection - Flowchart

  30. NOTE: • All computer languages therefore, provide some means of selection 4.5 Selection – Example 1 • When we need to take action based on user choice • In a menu of options, the user may input alternative choices • in consequence, the program must act on these choices

  31. 4.6 IF Statement and Logical Operators • All computer languages provide some means of selection • usually, in the form of an IF statement • IF statement (together with logical operators) is used to test for true or false • The action to be taken is preceded by the word THEN, and is only taken if the test result is true • IF a = b THEN PRINT “some message” • “a is equal to b” where the ‘=’ sign is the logical operator The logical operators used in pseudocode are: • = is equal to • >= is greater than or equal to • <= is less than or equal to • <> is not equal to

  32. NOTE: • The figure show screen display when the program is running 4.7 Selection – Example 2 • Shows the prompts provided for the user and the data the user keys in

  33. 4.7 Pseudocode Example PSEUDOCODE: Use variables choice OF TYPE character answer, number1, number2 OF TYPE Integer DISPLAY “Choose one of the following:” DISPLAY ”m for multiply” DISPLAY ”a for add” DISPLAY ”s for subtract” ACCEPT choice DISPLAY ”Input the numbers you want to use” ACCEPT number1, number2 IF choice = m THEN answer:= number1 * number2 ENDIF IF choice = a THEN answer:= number1 + number2 ENDIF IF choice = s THEN answer:= number1 - number2 ENDIF DISPLAY answer End program Note that these statements are indented. This indicates that they are part of the IF…THEN construct.

  34. PSEUDOCODE: If work = cat1 THEN p_rate:=“top” ELSE p_rate :=“normal” ENDIF 4.8 The IF…THEN..ELSE Statement • In an IF statement, the instructions following the THEN part of the IF statement are executed if the condition is TRUE • A more comprehensive set of conditions can be created by adding an ELSE statement • The IF … THEN … ELSE statement is used to deal with a situation such as • “A person is paid at the top level for category 1 work, otherwise his pay is at normal rates.” • There is some processing to do when the expression is FALSE • IF the work is category 1, THEN the pay rate is at the top level ELSE the pay rate is normal

  35. 4.8 The IF…THEN..ELSE Statement Some examples in English: Example 1: • If I’ve got an assignment to finish I’ll have to do it, otherwise I’ll go to see the football match with you next week. Example 2: • When the alarm goes off get out straight out of bed, unless it’s a weekend in which case you can stay in bed a bit longer

  36. 4.9 Definition IF..THEN…ELSE Statement • The most basic conditional construct in a programming language, allowing a choice of alternatives depending on the truth or falsity of a given condition.

  37. 4.11 The CASE Statement • The CASE statement is frequently used for coding the choice between item lists, such as those found in screen menus. Definition: • A conditional control structure that appears in most modern programming languages and allows a selection to be made between several (multiple) sets of program statements. • More general structure than the IF..THEN..ELSE statement.

  38. PSEUDOCODE: Use variables: category OF TYPE character insurance OF TYPE string ACCEPT category DO CASE of category CASE category = U PRINT Insurance := “not available” CASE category = A PRINT Insurance := “double” CASE category = B PRINT insurance := “normal” CASE category = M PRINT Insurance := “medically dependent” OTHERWISE PRINT “entry is invalid” ENDCASE ‘end of program 4.10 The IF…THEN..ELSE Statement Note that the last alternative statement in the CASE statement is OTHERWISE. This statement will be executed if no other case has been selected as TRUE. Some programming languages, such as C, use fall-through CASE structures and serious errors can arise if the OTHERWISE case is not included. You are advised to always include the OTHERWISE case in every CASE statement.

  39. EXAMPLE: English • “If had time and the money I would go on holiday” 4.12 Logical Operations • Conditions set in the IF .. THEN statements have been concerned with operands being equal • but there are many occasions when the conditions to be tested need to be extended • AND, OR, NOT, NAND, NOR, XOR • for example, IF a > b AND a > c THEN display “a is the largest”

  40. PSEUDOCODE: Use variables: mark OF TYPE Integer ACCEPT mark IF mark >= 80 THEN display “distinction” ENDIF IF mark >= 60 AND mark < 80 distinction THEN display “merit” ENDIF IF mark >= 60 AND mark < 80 THEN display “merit” ENDIF IF mark >= 40 AND mark < 60 THEN display “pass” ENDIF IF mark < 40 THEN display “fail” ENDIF ‘End of program 4.12 Logical Operations • The mark is a whole number between 1 and 100 • Grades are awarded according to the following criteria: • (>= 80 distinction) (>= 60 and < 80 merit) (>= 40 and < 60 pass) (< 40 fail)

  41. 4.13 Control Structure - LOOPS • The power of a computer lies in its ability to do things, time and time again, very quickly, without becoming inaccurate (precise and accurate) • The sequence of instructions which is repeated is called a loop • sometimes referred to as an iteration, but strictly speaking an iteration is more complex than a simple loop

  42. 4.14 Definition - LOOP • A sequence of instructions which is repeated until a prescribe condition, such as agreement with data element or completion of a count is satisfied. • This type of loop is often used for processing input data which will be coded item at the end of the data to indicate that the end of the data has been reached. • REPEAT an action for a block of actionsUNTIL (a true condition occurs)

  43. 4.15 Example LOOP • The instructions are in the form of a loop • will be repeated for every record on the payroll file • The loop will terminate when end-of-file is reached • the instruction after the loop will then be executed, • e.g. the pay slips would then be printed

  44. 4.16 Iteration • An iteration is a repetition of a sequence of instructions • the results from one pass of the loop are used as input to the instructions in the next pass of the loop Example: • If, during the running of the payroll loop, a running total was kept of : • e.g. tax to be paid • Each time through the loop, the tax for the current employee would be added to the previous total • Used as input in the following loop for the next employee

  45. 4.17 Elements of a Loop Two main elements: • A sequence of instructions to be performed each time the loop is executed • An indication of when to finish executing the loop Three constructs for Loops in pseudocode: • REPEAT UNTIL which tests at the end of a block of code, so the sequence of instructions are always repeated at least once • WHILE which tests at the start of a block of code so it is possible that the instructions in the loop may never be executed • FOR Loop which is controlled by a count given from known conditions

  46. PSEUDOCODE: Use variables: number of type Integer REPEAT DISPLAY “Enter a number between 0 and 100” ACCEPT number UNTIL number <0 or number > 100 end program NOTE: • Algorithm for only accepting a number between 1 and 100 4.18 REPEAT..UNTIL Loop

  47. 4.19 REPEAT..UNTIL Example PSEUDOCODE: Use Variables: letter OF TYPE Character athletics, swimming, football, badminton OF TYPE Integer REPEAT DISPLAY “Type in the letter chosen or Q to finish” DISPLAY “A : Athletics” DISPLAY “S : Swimming” DISPLAY “F : Football” DISPLAY “D : Badminton” DISPLAY “Q : end data:” ACCEPT letter IF letter = ‘A’ THEN athletics := athletics + 1 ENDIF IF letter = ‘S’ THEN swimming := swimming + 1 ENDIF IF letter = ‘F’ THEN football := football + 1 ENDIF IF letter = ‘B’ THEN badminton := badminton + 1 ENDIF UNTIL letter = ‘Q’ DISPLAY “Athletics scored ” athletics “votes” DISPLAY “Swimming scored ” swimming “votes” DISPLAY “Football scored ” football “votes” DISPLAY “Badminton scored ” badminton “votes” End program Explanation: • Another common uses in selection from a menu of options • Example - a survey carried out to discover the most popular sport • Results will be typed into the computer for analysis

  48. PSEUDOCODE EXAMPLE: Use variables: letter OF TYPE Character ACCEPT “letter” WHILE letter <> ‘q’ DISPLAY “the character you typed is “, letter ACCEPT letter ENDWHILE 4.20 WHILE Loop WHILE (a true condition) STATEMENT or STATEMENT BLOCK continued with ENDWHILE

  49. FOR (starting state, final state, increment) Statement Statement ENDFOR 4.21 FOR Loop • A FOR loop uses two values of a variable, the starting and the final condition for the action • The variable is incremented on each iteration until it reaches the value identified as the final state

More Related