Problem Solving for Programming Session 7 Data Types for Computer Programs
Data Types So far we have looked at several basic data types in this module: –Integer –Decimal/fractional –String –Boolean We also looked at how variables are created and initialized: –sugarsAdded 0 ; –parcelWeight 22.5 Kg ; –phoneNo ‘ ’ ; –milkRequired true ; We will now look at both of these topics in greater detail
Declaring Data Types In programming, whenever a variable is declared, its data type must be declared integer: numberOfSugars ; boolean: milkRequired ; Declaring variables as a particular data type helps in the allocation of computer memory: –Integer: 32 bits (Java) –Boolean: 1 bit (Java) It also helps to avoid typing errors –integer: parcelWeight ‘seven’ ;
Integer data types Programming tasks require us to work with a multitude of number sizes in computer programming (e.g. sugarsRequired, stadiumCapacity, distanceBetweenStars). Using one data type (e.g. integer) for all number ranges would therefore be inefficient. To account for different numerical ranges, most programming languages have several sub-types of integer: TypeMemory requiredRange of values byte8 bit shortinteger16 bit-32, ,767 integer/32 bit-2,147,483, ,147,483,647 longinteger64 bit-9223,372,036,854, 775, ,372,036,854, 775, 8087
Integer data types Which integer data types do you think would be applicable to the following variables? –populationOfCountry (geography) –squadNumber (football) –licenceEndorsements (driving) –employees (small/medium enterprise)
Declaring Variables Most programming languages allow us to declare a variables data type individually: byte: sugarsAdded ; shortinteger: parcelWeight ; shortinteger: payload ; Or to declare them collectively: byte: sugarsAdded ; shortinteger: parcelWeight, payload, capacity ;
Integer data types They also allow us to assign a value to a variable at the point of declaration: shortinteger: parcelWeight 0, payload 0, capacity 750 ;
Real (fractional) data types If the only numeric data types available to us were integer types, this would lead to some complex program code (e.g. How would we calculate 17÷9 using only integers?) To account for this, all programming languages come with real data types. Real data types allow us to represent any number that has a fractional element real: pi ; (constant) real: sizeOfVirus ;
Mathematical Operators for Integer and Real Data Earlier we saw that a data type is defined not only by the values it can take, but also by the operations that can be performed on it: Where numerical data types are concerned, the following operators apply:
Mathematical Operators for Integer and Real Data OperatorMeaningUsageResultBinary/unary ^Exponentiation9^3729binary X (or *) Multiplication2 x 36binary ÷ (or (/)Divisionbinary MODGives remainder of division 11 MOD 32binary +Addition2 + 35binary -Subtraction3 – 21binary +Makes the value of its operand positive +3 unary -Makes the value of its operand negative -3 unary
Operator precedence Mathematical operators can be combined to allow expressions such as: integer: result x 6 ; What would be the result of this expression be? Obviously it depends on which way round we do it. –(3+4) * 6 = 42 –3 + (4 * 6) = 27 However, a computer program would always evaluate the expression as 27. Why?
Operator precedence Precedence levelOperatorDescription 1()Parenthesis 2^Exponentiation 3unary +, unary -unary positive, unary negative 4x, ÷, MODMultiplication, division, modulus 5+ -Addition, subtraction 6=, ≠,, >=, <=Relational operators (equals, not equal to, less than, greater than, etc....) Given these rules what would be the result of the following pseudo code snippet: boolean: result: IF (3^3 ÷ < 7 * (2 – 1)) result true ; ELSE result false ; ENDIF Because programming languages have an order of precedence when it comes to mathematical operations.
Characters and Strings String and character data types are used to represent data which is neither numeric nor boolean. All strings are collections of characters. E.g. the name ‘David Smith’ is a collection of 11 characters: D + a + v + i + d + ‘ ’ + S + m + i + t + h Because strings are collections of characters we have a way of performing some basic operations on them (e.g. sorting a list of names, or working out a customer’s initials) string: firstInitial firstName[0] ; string: lastInitial lastName[0] ; string: initials firstInitial + lastInitial ; Character at position zero in the string
Characters and Strings All characters belong to a particular characterset (e.g. English, Japanese or Arabic). Each character in any character set is represented by a unique ASCII code (American Standard Code for Information Interchange)
Characters and Strings The ASCII code is a numerical (decimal) representation of a character: –A (65) –a (97) –! (33) By giving a character a decimal code, the character can be transposed into a binary number and can therefore be stored in computer memory.
Boolean Data Types We encountered Boolean data types earlier in this module (e.g. milkRequired) We saw that a Boolean can only ever take a value of yes or no (true or false) We also saw how Booleans could be used to form the conditions for conditional and repetition structures IF (milkRequired) Add milk ; ENDIF WHILE (NOT payNow)AND(productCount < 11) Scan Item ; itemsScanned itemsScanned + 1 ; Display Pay Now button ; Get payNow ; ENDWHILE
Declaring and Assigning Values to Boolean Variables As we have seen a boolean can be assigned a value of true or false: boolean: isAdult false ; A boolean can also be assigned the value of an expression: boolean: isAdult (age <= 18) ; boolean: vanFull (payload + parcelWeight > 750) ;
Using Booleans as Flags to Control Iterations We can think of a Boolean as a flag: a raised flag corresponds to true and a lowered flag corresponds to false. Boolean flags are often employed as sentinels to determine the point at which an iteration structure should be exited.
Using Booleans as Flags to Control Iterations 1. integer: number, 2. square ; 3. character: response ; 4. boolean: finished ; 5. DO 5.1 Display ‘Enter a number :’ ; 5.2 get value of number; 5.3 square number * number ; 5.4 Display ‘Your number squared is ‘ ; 5.5 Display square ; 5.6 Display ‘Do you want another go? Y/N’ 5.7 Get value of response ; 5.8 finished (response = ‘N’) OR (response = ‘n’) ; WHILE (NOT finished)
Boolean Operators Like numeric data types, Boolean data types are defined by the operations available to them. There are three (basic) Boolean operators, two of which we have already encountered: –AND –OR –NOT The outcome of logical operators is always a Boolean true or false value
Combining Operands with AND or OR Where two or more operands (expressions) are connected by an AND operator, both conditions must be true in order for the outcome of the statement to be true: boolean: grantVisa false ; integer: age ; boolean: isEUCitizen ; Get age ; Get isEUCitizen ; IF (age >= 16) AND (isEUCitizen) grantVisa true ; ENDIF What would be the outcome if: –age 13 and Colombian –age 16 and Jamaican –age 16 and Italian
Combining Operands with AND or OR Where two or more operands are connected by an OR operator, if either of the conditions is true, the outcome of the statement is true: boolean: grantVisa false ; integer: age ; boolean: isEUCitizen ; Get age ; Get isEUCitizen ; IF (age <= 16) OR (isEUCitizen) grantVisa true ; ENDIF What would be the outcome if: –age 13 and Canadian –age 17 and Indian –age 16 and Danish
Negating a Boolean value with the NOT Operator NOT inverts or negates the value of its associated operand: WHILE NOT(conveyorIsEmpty) Process parcels... ENDWHILE WHILE NOT (payNow) Scan Items ; ENDWHILE
Boolean Logic The following truth table illustrates the results the results that the three operators (AND, OR, and NOT) give for all permutations of their operands (p & q). Value of pValue of qP AND qP OR qNOT pNot q false true falsetruefalsetrue false truefalse truefalsetrue false
Boolean Logic Consider the following problem: An algorithm has been devised to calculate the average marks of a class. A teacher enters the mark for each student along with each student’s name. Entering ‘ZZZZZ’ and a mark of zero signals the end of the data and at this point the average mark for the class is calculated.
Boolean Logic The algorithm may look something like the following: 1. string: name ; 2. integer mark, 3. total, 4.numberOfMarks ; 5. total 0 ; 6. numberOfMarks 0 ; 7. Get name and mark ; 8. WHILE (name ≠ ‘ZZZZZ’) AND (mark ≠ 0) 8.1 total total + mark ; 8.2 numberOfMarks numberOfMarks + 1 ; 8.3 Get next name and mark END WHILE //code to calculate average mark
Boolean Logic At first glance the solution looks good, Unfortunately, though, it will not suffice. This is because the condition at #8 means that the loop will terminate as soon as a mark of zero is entered, even if name is different than ‘ZZZZZ’. The following truth table shows this clearly WHILE (name ≠ ‘ZZZZZ’) AND (mark ≠ 0) variablesConditionsContinue loop? name (p)Mark (q) pqp AND q SMITH89true Yes ZZZZZ0false No HIGGINS0truefalse No ZZZZZ54falsetruefalseNo
Boolean Logic The correct solution for this problem replaces the AND with an OR 1. string: name ; 2. integer mark, 3. total, 4.numberOfMarks ; 5. total 0 ; 6. numberOfMarks 0 ; 7. Get name and mark ; 8. WHILE (name ≠ ‘ZZZZZ’) OR (mark ≠ 0) 8.1 total total + mark ; 8.2 numberOfMarks numberOfMarks + 1 ; 8.3 Get next name and mark END WHILE //code to calculate average mark
Boolean Logic A truth table demonstrates why this is correct WHILE (name ≠ ‘ZZZZZ’) OR (mark ≠ 0) variablesConditionsContinue loop? name (p)Mark (q) pqp OR q SMITH89true Yes ZZZZZ54falsetrue Yes HIGGINS0truefalse Yes ZZZZZ0false No
Boolean Logic In both example algorithms, we have started with a condition that will be true each time the loop iterates: WHILE (name ≠ ‘ZZZZZ’) AND (mark ≠ 0) WHILE (name ≠ ‘ZZZZZ’) OR (mark ≠ 0) An alternative approach, and one that dispenses with the OR, would be to start instead with condition that would be true when the loop terminates: WHILE (name=‘ZZZZZ’) AND (mark=0) If we negate this condition, then any values apart from ‘ZZZZZ’ and 0 will cause the loop to continue. But we must negate the condition as a whole. WHILE NOT((name=‘ZZZZZ’) AND (mark=0)) Again, a truth table demonstrates why this is correct
Boolean Logic WHILE NOT((name=‘ZZZZZ’) AND (mark=0)) variablesConditionsContinue loop? name (p) Mark (q) pqp AND qNOT(P&Q) SMITH89False TrueYes HIGGINS0FalseTrueFalseTrueYes ZZZZZ54TrueFalse TrueYes ZZZZZ0True FalseNo