problem solving for programming

31
Problem Solving for Programming Session 7 Data Types for Computer Programs

Upload: elaine-lowery

Post on 31-Dec-2015

22 views

Category:

Documents


1 download

DESCRIPTION

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 ; - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Problem Solving for Programming

Problem Solving for Programming

Session 7Data Types for Computer Programs

Page 2: Problem Solving for Programming

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 ‘020 7631 6805’ ;– milkRequired true ;

• We will now look at both of these topics in greater detail

Page 3: Problem Solving for Programming

Declaring Data Types

• In programming, whenever a variable is declared, its data type must be declaredinteger: 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’ ;

Page 4: Problem Solving for Programming

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:

Type Memory required Range of values

byte 8 bit -128 . . . 127

shortinteger 16 bit -32,768 . . .32,767

integer/ 32 bit -2,147,483,648 . . . 2,147,483,647

longinteger 64 bit -9223,372,036,854, 775, 808 . . .9223,372,036,854, 775, 8087

Page 5: Problem Solving for Programming

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)

Page 6: Problem Solving for Programming

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 ;

Page 7: Problem Solving for Programming

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 ;

Page 8: Problem Solving for Programming

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 elementreal: pi 3.147 ; (constant)

real: sizeOfVirus 0.009347678 ;

Page 9: Problem Solving for Programming

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:

Page 10: Problem Solving for Programming

Mathematical Operators for Integer and Real Data

Operator Meaning Usage Result Binary/unary

^ Exponentiation 9^3 729 binary

X (or *) Multiplication 2 x 3 6 binary

÷ (or (/) Division binary

MOD Gives remainder of division

11 MOD 3 2 binary

+ Addition 2 + 3 5 binary

- Subtraction 3 – 2 1 binary

+ Makes the value of its operand positive

+3 +3 unary

- Makes the value of its operand negative

-3 -3 unary

Page 11: Problem Solving for Programming

Operator precedence

• Mathematical operators can be combined to allow expressions such as:

integer: result 3 + 4 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?

Page 12: Problem Solving for Programming

Operator precedence

Precedence level Operator Description

1 () Parenthesis

2 ^ Exponentiation

3 unary +, unary - unary positive, unary negative

4 x, ÷ , MOD Multiplication, 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 ÷ 9 + 20 < 7 * (2 – 1)) result true ;ELSE result false ; ENDIF

• Because programming languages have an order of precedence when it comes to mathematical operations.

Page 13: Problem Solving for Programming

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

Page 14: Problem Solving for Programming

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)

Page 15: Problem Solving for Programming

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.

Page 16: Problem Solving for Programming

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

Page 17: Problem Solving for Programming

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) ;

Page 18: Problem Solving for Programming

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.

Page 19: Problem Solving for Programming

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)

Page 20: Problem Solving for Programming

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

Page 21: Problem Solving for Programming

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

Page 22: Problem Solving for Programming

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

Page 23: Problem Solving for Programming

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

Page 24: Problem Solving for Programming

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 p Value of q P AND q P OR q NOT p Not q

false false false false true true

false true false true true false

true false false true false true

true true true true false false

Page 25: Problem Solving for Programming

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.

Page 26: Problem Solving for Programming

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

Page 27: Problem Solving for Programming

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)

variables Conditions Continue loop?

name (p) Mark (q) p q p AND q

SMITH 89 true true true Yes

ZZZZZ 0 false false false No

HIGGINS 0 true false false No

ZZZZZ 54 false true false No

Page 28: Problem Solving for Programming

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

Page 29: Problem Solving for Programming

Boolean Logic

• A truth table demonstrates why this is correct

WHILE (name ≠ ‘ZZZZZ’) OR (mark ≠ 0)

variables Conditions Continue loop?

name (p) Mark (q) p q p OR q

SMITH 89 true true true Yes

ZZZZZ 54 false true true Yes

HIGGINS 0 true false false Yes

ZZZZZ 0 false false false No

Page 30: Problem Solving for Programming

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

Page 31: Problem Solving for Programming

Boolean Logic

WHILE NOT((name=‘ZZZZZ’) AND (mark=0))

variables Conditions Continue loop?

name (p)

Mark (q) p q p AND q NOT(P&Q)

SMITH 89 False False False True Yes

HIGGINS 0 False True False True Yes

ZZZZZ 54 True False False True Yes

ZZZZZ 0 True True True False No