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

Slides:



Advertisements
Similar presentations
Types and Arithmetic Operators
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Problem Solving for Programming Session 6 Data and Control Abstractions.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
CIS 234: Using Data in Java Thanks to Dr. Ralph D. Westfall.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
10 November JavaScript. Presentation Hints What do YOU think makes a good presentation Some of my suggestions Don’t write full sentences on slides Talk,
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
JavaScript, Fourth Edition
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
Programming Logic and Design, Introductory, Fourth Edition1 Understanding Computer Components and Operations (continued) A program must be free of syntax.
1 Lab Session-III CSIT-120 Spring 2001 Revising Previous session Data input and output While loop Exercise Limits and Bounds GOTO SLIDE 13 Lab session.
21 March, 2000 CS1001 Lecture 4 Data Types + Algorithms = Programs Data Types & Arithmetic Errors Arithmetic Operators and Functions Program Testing Tips.
Objectives You should be able to describe: Data Types
CPS120: Introduction to Computer Science Lecture 8.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Lesson 2 McManus COP  Computational ◦ problems involving some kind of mathematical processing  Logical ◦ Problems involving relational or logical.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CIS Computer Programming Logic
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
2440: 211 Interactive Web Programming Expressions & Operators.
Computer Science Selection Structures.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Input, Output, and Processing
1 Conditional statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
Problem Solving for Programming Session 8 Static Data Structures.
UniMAP Sem1-07/08EKT120: Computer Programming1 Week2.
BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA TYPES AND OPERATIONS.
Arithmetic Operations. Review function statement input/output comment #include data type variable identifier constant declaration.
CHAPTER 4: CONTROL STRUCTURES - SEQUENCING 10/14/2014 PROBLEM SOLVING & ALGORITHM (DCT 1123)
Selection Boolean What is Boolean ? Boolean is a set with only two values : –true –false true and false are standard identifiers in Pascal, called Boolean.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
© ABB University - 1 Revision C E x t e n d e d A u t o m a t i o n S y s t e m x A Chapter 11 Structured Text Course T314.
Beginning Problem-Solving Concepts for the Computer
Primitive Variables.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
COMP Primitive and Class Types Yi Hong May 14, 2015.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Variables Continued In the last session we saw how variables are objects that allow us to store values in the RAM of the computer In this session we shall.
An Object-Oriented Approach to Programming Logic and Design Chapter 5 Making Decisions.
Fundamental Programming Fundamental Programming More Expressions and Data Types.
Data Handling in Algorithms. Activity 1 Starter Task: Quickly complete the sheet 5mins!
Flow of Control Joe McCarthy CSS 161: Fundamentals of Computing1.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 5 Making Decisions.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
What will each of the following lines print? System.out.println("number" ); number645 System.out.println("number" + (6 + 4)+ 5); number105 System.out.println(6.
Copyright © Curt Hill The C++ IF Statement More important details More fun Part 3.
 Type Called bool  Bool has only two possible values: True and False.
7 - Programming 7J, K, L, M, N, O – Handling Data.
IGCSE 4 Cambridge Data types and arrays Computer Science Section 2
ITEC113 Algorithms and Programming Techniques
Object Oriented Programming
The System.exit() Method
Boolean Expressions to Make Comparisons
Presentation transcript:

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