Presentation is loading. Please wait.

Presentation is loading. Please wait.

Problem Solving for Programming Session 6 Data and Control Abstractions.

Similar presentations


Presentation on theme: "Problem Solving for Programming Session 6 Data and Control Abstractions."— Presentation transcript:

1 Problem Solving for Programming Session 6 Data and Control Abstractions

2 Data Identify the variables in this current account statement.

3 Data types VariablesData Type accountName accountNumber branchCode statementNumber transactionDate transaction transactionDescription amountWithdrawn amountPaidIn balance Each of the variables in the current account statement can be represented at a higher level of abstraction by a data type: - Whole number (integer) - Decimal number (fractional) - Date/time - Textual data (character, string) Match each of the variables in the table with an appropriate data type.

4 Data abstractions Data types are defined by the range of values that they can hold and by the types of operations that can be performed on them. For example, whole numbers, or integers, can hold any value between 0 and infinity, and several operations can be performed on them (e.g. x + ÷ -). Textual data types, on the other hand, can hold any character or collection of characters (alphabetic or numeric) in any order.

5 Numeric data types Whole numbers/Integers (e.g. 3, 17, 60,897). Decimal numbers (e.g. 1.3, 2.88, 0.09897). If you were going to add, subtract or multiply whole numbers in a program, you would declare your data type as Integer. But what about division (e.g. 17 ÷ 9)? would you declare your data type as a Integer or decimal?

6 Textual data types Character data (e.g. 3, “, ©, A, a) String data (e.g. Birkbeck, 02076316851, Dave) Why do we have the two types? Why not just string? What kind of operations can be performed on string data? Can we add string data elements (e.g. XX + YY)?

7 Textual data types The answer is yes, but the answer would probably be something like XXYY rather than ZZ. This is because the operator + works in a different way for string data. It concatenates (joins) rather than adds in the mathematical sense of adding.

8 Boolean data types Recall in our coffee making problem we created a variable called milkRequired. This is a special type of variable called a Boolean. Booleans take either a true (yes) or a false (no) value. No other values are possible. milkRequired? You either want milk (true) or you do not want milk (false). overTwentyOne? You are either over 21 (true) or you are not (false).

9 Typing Programming languages restrict which data types can be combined together. Strongly typed languages (e.g. Ada) will not permit an expression such as 15 + X, because one value is an integer and the other is character data. Less strongly typed languages (e.g. BASIC), however, may allow 15 + X. To do this they would first transform X into an integer type and then add the two values together: 15 + 88 = 103 (88 being the ascii value of the character ‘X’)

10 Control Abstractions - Extended choice So far we have looked at how to solve simple problems of choice. IF (milk required) Add milk ; ENDIF In this example, the choice available is between milk and a null action (e.g. Do something or do nothing). However, what would happen if the choice was between two or more positive outcomes (e.g. Do something or do something else)?

11 Control Abstractions - Extended choice Consider an ATM transaction. If there are sufficient funds in the account, the ATM will dispense cash; otherwise it will display an ‘insufficient funds’ message. How could this be expressed in pseudo code?

12 Control Abstractions - Extended choice One approach would be to use two IF statements : IF (funds available) Dispense cash ; ENDIF IF (insufficient funds available) Display message of apology ; ENDIF The above approach would work, but it is inelegant: it makes the two choices appear as if they are both available, when, in fact, they are mutually exclusive. You cannot have funds and no funds.

13 Control Abstractions - Extended choice A more appropriate approach would be to combine the choices into an IF.. ELSE.. ENDIF statement. IF (funds available) Dispense cash ; ELSE Display message of apology ; ENDIF What about if we were faced with a problem of several choices? Imagine in the van loading problem from the previous session that in order to protect loaders from back injuries, parcels are given weight labels. Parcels 5 kg and under are labelled light, parcels over 5 kg, but lighter than 10 kg, medium, and 10 kg or over heavy.

14 Control Abstractions - Extended choice In such cases, we can include additional conditions by using an IF.. ELSEIF.. ELSE.. ENDIF construct. IF (parcelWeight up to 5 kilos) Add 'light' sticker ; ELSEIF (parcelWeight less than 10 kilos) Add 'medium' sticker ; ELSE Add 'heavy' sticker ; ENDIF Load parcel on van ; In plain English: If it is a light parcel, add a light label; otherwise if it is a medium parcel, add a medium label, otherwise add a heavy label. Why is there no third condition (e.g. IF (parcel weight more than 10kg))?

15 Relational operators We can use relational operators for statements that make comparisons between different values. OperatorSymbol Less than< Less than or equal to≤ Equals (equality)= Grater than or equal to≥ Greater than> Not equal to≠

16 Relational operators IF (parcelWeight ≤ 5 kilos) Add 'light' sticker ; ELSEIF (parcelWeight < 10 kilos) Add 'medium' sticker ; ELSE Add 'heavy' sticker ; ENDIF Load parcel on van ; Write a conditional statement for the following example using an IF, ELSE IF, ELSE, ENDIF construct. In a university the grades A to F are awarded for the following marks: A= more than 79; B=between 70 and 79; C=between 60 and 69; D=between 50 and 59; E=between 40 and 49; F=anything less than 40.

17 Relational operators Optimum solution IF (mark ≥ 80) grade ← ‘A’ ; ELSEIF (mark ≥ 70) grade ← ‘B’ ; ELSEIF (mark ≥ 60) grade ← ‘C’ ; ELSEIF (mark ≥ 50) grade ← ‘D’ ; ELSEIF (mark ≥ 40) grade ← ‘E’ ; ELSE grade ← ‘F’ ; ENDIF Why not IF (mark ≥ 80) grade ← ‘A’ ; ELSEIF (mark ≥ 70 AND mark ≤ 79) grade ← ‘B’ ;.... ENDIF

18 Control Abstractions - Extended choice Very often one choice we make directly depends upon another choice. If it is raining, I’ll stay indoors; otherwise, I’ll go for a walk. If I stay indoors, I’ll go to the café if it’s before closing time; if not, I’ll stay at home instead. Raining  café or home Not raining  walk How might this be expressed in an IF, ELSE, ENDIF structure?

19 Control abstractions - Nested IF statements IF (isRaining) IF (currentTime < closingTime - 30) Go to café ; ELSE Stay at home ; ENDIF ELSE Go for walk ; ENDIF Here we have one IF statement nested inside another IF statement.

20 Control abstractions - Nested IF statements Consider the following problem: You want to develop a program that attributes the number of days to each month depending upon its length (e.g. January = 31; April = 30). How would you tackle this problem using nested IF statements? (hint: February has either 28 or 29 days depending upon whether it is a leap year. Months can be numbered 1 to 12).

21 Control abstractions - Nested IF statements IF (month = 4) OR (month = 6) OR (month = 9) OR (month = 11) daysInMonth ← 30 ; ELSE IF (month = 2) IF (isLeapYear) daysInMonth ← 29 ; ELSE daysInMonth ← 28 ; ENDIF ELSE daysInMonth ← 31 ; ENDIF What data type is the variable isLeapYear?

22 Control abstractions - Iteration structures There are several ways of classifying and understanding iterations (loop structures). Determinate: one in which the number of times the action block is to be repeated is known in advance or can be calculated at the time the loop is executed. Indeterminate one in which the number of iterations is unknown in advance and cannot be calculated.

23 Determinate and indeterminate loops Find out how many sugars required ; WHILE (sugars added is not equal to sugars required) Add spoonful of sugar ; Add 1 to number of sugars added ; ENDWHILE WHILE (conveyor not empty) payload  zero ; WHILE (payload + parcelWeight is less than or equal to capacity) load parcel on van ; Add parcelWeight to payload; Get next parcelWeight ; ENDWHILE Despatch van ; ENDWHILE Which of the above loops is determinate and which is indeterminate? Why?

24 Determinate and indeterminate loops The first loop is determinate (We know in advance how many sugars our guests want, and therefore we know how many times the loop will iterate). The second loop is indeterminate (We do not know how many parcels there will be for delivery on any given day).

25 Read ahead, and read and process loops In a read ahead loop, the first item to be processed is fetched before the WHILE structure commences. The next item is fetched after the action block. We use a read ahead loop, when information about the first item to be processed is needed in order to test the loop’s controlling condition. Get parcelWeight ; WHILE (payload + parcelWeight ≤ capacity ) Load item on van ; payload  payload + parcelweight ; Get next parcelWeight ; ENDWHILE

26 Read ahead, and read and process loops In a read and process loop the first item is fetched immediately after the WHILE loop is entered. We use a read and process loop when we do not need to know anything about the items to be processed in advance. WHILE (itemsRemaining) Get an item ; Add item to collection ; ENDWHILE

27 Zero or more loops A zero or more loop tests its condition at the start. As a result, the condition can be false before any actions are carried out resulting in zero iterations of the loop. sugarsAdded ← 0 ; sugarsRequired ← 0 ; WHILE (sugarsAdded < sugarsRequired) Add sugar ; sugarsAdded ← sugarsAdded + 1 ; ENDWHILE In this case, if the guest does not want sugar, the loop will iterate zero times because both sugarsAdded and sugarsRequired will have a value of zero and the test condition will be false.

28 At least once loops For some programs, however, we need the loop to iterate at least once. For example an ATM. PIN ← -1 ; WHILE (PIN ≠ storedPIN) Display ‘Enter your PIN’ ; Get PIN ; ENDWHILE Display account details ; This solution appears to work. However, it is somewhat inelegant as we have to use a dummy pin number (-1) to begin the sequence. Can you think of an alternative way of solving the problem?

29 At least once loops A more elegant solution would be to test the condition after the action block has been carried out. This can be done with a DO.. WHILE loop. DO Display ‘Enter your PIN’ ; Get PIN ; WHILE (PIN ≠ storedPIN) Display account details ; In this type of loop, the action block is executed before the conditional statement is encountered. If the condition is true, the action block is repeated (In this case, it is repeated until a correct PIN is entered). Can you see any potential weaknesses with the solution as it stands? Think about your own experience of ATMs.

30 WHILE or DO WHILE? 1.You are required to calculate and display the average age of a class of children. Children’s ages will be entered one at a time. When there are no more ages to enter, the user will enter zero and at that point the program will display the average age of the class. 2.A school has been having trouble on site, so it decides to fit a swipe card system for entry to its classrooms. Students are prompted by a display to swipe their cards to enter each room. If the code stored in the card, is not valid, then the student is asked to re-swipe their card. If the code is valid, then a ‘Please Enter’ message is displayed and the door opens automatically. In which problem would a DO.. WHILE loop be preferable? In which would a WHILE loop be preferable? Write the pseudo code for each scenario.

31 FOR Loops Because count-controlled loops are so common,, most languages have a specialised iteration construct for them. The FOR Loop is the most common of these constructs. FOR variable GOES FROM initial value TO final value Action block ; ENDFOR The number of times FOR loops iterate depends on the initial and final values in the FROM, TO part of the loop.

32 FOR Loops A FOR loop is simply a simplified WHILE loop in many respects. The following examples do exactly the same thing. Month  1 ; WHILE (month <=12) Display 'Please enter the month's rainfall' ; Get monthRainfall ; totalRainfall ← totalRainfall + monthRainfall ; month  month + 1 ; ENDWHILE FOR month GOES FROM 1 TO 12 Display 'Please enter the month's rainfall' ; Get monthRainfall ; totalRainfall ← totalRainfall + monthRainfall ; ENDFOR

33 FOR Loops The FOR Loop is somewhat more elegant. The initialization and incrementing of month is done automatically, unlike the WHILE loop where it needs to be done explicitly. How many times will the following FOR Loops iterate? FOR letter GOES FROM 'A' TO 'Z' Display letter ; ENDFOR FOR year GOES FROM age TO age + 10 Action block ; ENDFOR (Where the initial value of age is 38)

34 Session reading Vickers – Chapter 5


Download ppt "Problem Solving for Programming Session 6 Data and Control Abstractions."

Similar presentations


Ads by Google