Lecture 19: Simple Data Types. 2 Lecture Contents: t Representation and conversion of numeric types t Representation and conversion of type char t Enumerated.

Slides:



Advertisements
Similar presentations
Data Types H&K Chapter 7 Instructor – Gokcen Cilingir Cpt S 121 (July 12, 2011) Washington State University.
Advertisements

Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 6. Simple and User Defined Data Types.
Types and Variables. Computer Programming 2 C++ in one page!
Sizes of simple data types sizeof(char) = 1 size(short) = 2 sizeof(int) = 4 size(long) = 8 sizeof(char) = 1 size(short) = 2 sizeof(int) = 2 size(long)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Introduction.
Lab 10 rRepresentation And Conversion of Numeric Types l Difference between Numeric Types l Automatic conversion of Data types l Explicit Conversion of.
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Sixth.
1 CSC 1401 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Introduction.
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
Chapter 2: Introduction to C++.
Basic Elements of C++ Chapter 2.
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
Simple Data Type Representation and conversion of numbers
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Seventh.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
Lecture 9m: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
CS2311 Computer Programming Dr. Yang, Qingxiong (with slides borrowed from Dr. Xu, Henry) Lecture 2: Basic Syntax – Part I: Variables and Constants.
Copyright © 2002 W. A. Tucker1 Chapter 7 Lecture Notes Bill Tucker Austin Community College COSC 1315.
3. The Nuts and Bolts of C++ Computer Programming 3. The Nuts and Bolts of C++ 1 Learning the C++ language 3. The Nuts and Bolts of C++ (4)
Chapter 7 Simple Date Types J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Chapter 6 Fundamental Types Dept of Computer Engineering Khon Kaen University.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Simple Data Types Problem Solving, Abstraction, and Design using.
Chapter 2: Using Data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Simple Data Types Built-In and User Defined Chapter 10.
ISBN Chapter 6 Data Types Introduction Primitive Data Types User-Defined Ordinal Types.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Sixth.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
1 Objects Types, Variables, and Constants Chapter 3.
7. BASIC TYPES. Systems of numeration Numeric Types C’s basic types include integer types and floating types. Integer types can be either signed or unsigned.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Chapter Topics The Basics of a C++ Program Data Types
Chapter 2: Introduction to C++
Tokens in C Keywords Identifiers Constants
Basic Elements of C++.
Fundamental Data Types
Basic Elements of C++ Chapter 2.
Introduction to Abstract Data Types
Lectures on Numerical Methods
Chapter 2: Introduction to C++.
Presentation transcript:

Lecture 19: Simple Data Types

2 Lecture Contents: t Representation and conversion of numeric types t Representation and conversion of type char t Enumerated types t Demo programs t Exercises

3 Basic topics Classification of Data Types: / \ Standard (predefined) Abstract: user defined bool, enumerated char, abstract UDT - OOP int, short, long, unsigned, float, double

4 Basic topics Definition Simple data type: Data type used to store a single value. Such data types are often referred to as: –simple data types or –scalar data types.

5 Simple Data Types Classification: Symbolic: character. Internal representation ASCII, EBCDIC, UNICODE; Numeric1: integer and enumerated. Internal representation based on fixed point format. Numeric2: real. Internal representation based on floating point format: mantissa and exponent. Implicit conversion of data types: Explicit conversion of data types: cast operator or (type) operator.

6 Simple Data Types Implicit and explicit conversion of data types: cast operator or (type) operator. int a, b, c, d; a = 6.778;// implicit conversion cout << a;

7 Simple Data Types Implicit and explicit conversion of data types: cast operator or (type) operator. int a, b, c, d; a = 6.778;// implicit conversion b = (int)6.778;// explicit conversion cout << a << endl; cout << b << endl;

8 Simple Data Types Implicit and explicit conversion of data types: cast operator or (type) operator. int a, b, c, d; a = 6.778;// implicit conversion b = (int)6.778;// explicit conversion c = int(6.778);// explicit conversion cout << a << endl; cout << b << endl; cout << c << endl;

9 Simple Data Types Implicit and explicit conversion of data types: cast operator or (type) operator. int a, b, c, d; a = 6.778;// implicit conversion b = (int)6.778;// explicit conversion c = int(6.778);// explicit conversion d = static_cast (6.778); // explicit conversion cout << a << endl; cout << b << endl; cout << c << endl; cout << d << endl;

10 User defined enumerated types: Examples for boolean enumerated data type: enum boolean { NO, YES }; OR typedef enum { NO, YES } boolean; boolean a, flag = YES;

11 User defined enumerated types: Examples for weekday enumerated data type: enum weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; OR typedef enum {Mon,Tue,Wed,Thu,Fri,Sat,Sun} weekday; weekday today = Fri, tomorrow = Sat;

12 User defined enumerated types: Examples for weekday enumerated data type: enum weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; weekday day, today=Fri, tomorrow=Sat; cout << endl << today; cout << endl << tomorrow; for (day=Mon; day <= Sun; day=day+1) // Attention! cout << endl << day; // Compile the code and read the error message

13 User defined enumerated types: Examples for weekday enumerated data type: enum weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; weekday day, today=Tue, tomorrow=Wed; cout << endl << today; cout << endl << tomorrow; for (day=Mon; day <= Sun; day=weekday(day+1)) cout << endl << day;

14 User defined enumerated types: Examples for weekday enumerated data type: enum weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; weekday day, today=Tue, tomorrow=Wed; cout << endl << today; cout << endl << tomorrow; for (day=Mon; day <= Sun; day=(weekday)(day+1)) cout << endl << day;

15 User defined enumerated types: Examples for weekday enumerated data type: enum weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; weekday day, today=Tue, tomorrow=Wed; cout << endl << today; cout << endl << tomorrow; for (day=Mon; day (day+1)) cout << endl << day;

16 User defined enumerated types: Examples for weekday enumerated data type: enum weekday { Mon=1, Tue, Wed, Thu, Fri, Sat, Sun }; weekday day, today=Tue, tomorrow=Wed; cout << endl << today; cout << endl << tomorrow; for (day=Mon; day <= Sun; day=weekday(day+1)) cout << endl << day;

17 User defined enumerated types: Examples for month enumerated data type: enum month {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; OR typedef enum {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec} month; month thisMonth=Nov, nextMonth; nextMonth = thisMonth + 1; // Attention!

18 User defined enumerated types: Examples for month enumerated data type: enum month {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; OR typedef enum {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec} month; month thisMonth=Nov, nextMonth; nextMonth = month(thisMonth + 1);

19 More on Simple Data Types Extract from Friedman/Koffman, chapter 7

Simple Data Types Chapter 7

Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value –Programming practices const type identifier = constant; const int FileSize = 4096;

22 #define t An additional way to define constants t Used in older C programs prior to introduction of constants #define identifier replacement-text #define pi The same as const double pi = ;

Internal Representations of int and float t float, double and int used to represent numbers t Stored differently in the computer memory t int stored as binary 1s and 0s –sign and binary number t float, double stored in 2 parts plus the sign –sign - characteristic - mantissa –Value of float number = mantissa * 2 characteristic

24 Value Variations t Three sizes of integer data type –short int –int –long int t Each uses a different amount of the computers memory –long and short provide consistency between compilers –short can save lots of memory

25 Value Variations t Three sizes of real data type –float –double –long double t Each uses a different amount of the computers memory –double is no less precise than float –long double provides less?? precision than double

26 Numerical Inaccuracies t Can have errors when using float in some computations t Do to the way floats are stored t Errors will be determined by the number of binary bits used in the mantissa t Arithmetic underflow and arithmetic overflow –Multiplying 2 small or 2 large numbers together respectively

27 Ranges for int and float Constants t See tables on next two slides t Definitions for some of these C++ constants are in the, and, libraries t The actual values of these constants will vary from computer to computer

28 Extract from #define SCHAR_MIN (-128) /* minimum signed char value */ #define SCHAR_MAX 127 /* maximum signed char value */ #define UCHAR_MAX 0xff /* maximum unsigned char value */ #define SHRT_MIN (-32768) /* minimum (signed) short value */ #define SHRT_MAX /* maximum (signed) short value */ #define USHRT_MAX 0xffff /* maximum unsigned short value */ #define INT_MIN ( ) /* minimum (signed) int value */ #define INT_MAX /* maximum (signed) int value */ #define UINT_MAX 0xffffffff /* maximum unsigned int value */ #define LONG_MIN ( L - 1) /* minimum (signed) long value */ #define LONG_MAX L /* maximum (signed) long value */ #define ULONG_MAX 0xffffffffUL /* maximum unsigned long value */

29 Extract from #define DBL_DIG 15 /* # of decimal digits of precision */ #define DBL_MAX e+308 /* max value */ #define DBL_MIN e-308 /* min positive value */ #define FLT_DIG 6 /* # of decimal digits of precision */ #define FLT_MAX e+38F /* max value */ #define FLT_MIN e-38F /* min positive value */

30 The sizeof() operator This operator returns the number of bytes needed to allocate memory for a certain data type. cout << sizeof(int) << endl; cout << sizeof(long) << endl; cout << sizeof(short) << endl; cout << sizeof(float) << endl; cout << sizeof(double) << endl;

31 The sizeof() operator This operator returns the number of bytes needed to allocate memory for a certain data type. int a; cout << sizeof(a) << endl; long b;cout << sizeof(b) << endl; short c;cout << sizeof(c) << endl; float d;cout << sizeof(d) << endl; double e;cout << sizeof(e) << endl;

32 Mixing Types t The notion of type promotion –promoting a lower type to a higher type example: 3 + x /2 –if x is float, constant 2 would be promoted to float as well and actually be 2.0 t Type conversions –int to float (number.0) –float to int (truncation occurs)

33 Mixing Types t Example: int y; float x = 3.89; y = x; y would contain 3

34 Type Casting t Avoid mixing types but if you need to, you can cast a type t Type casting allows you to change a type within the program for a specific function Two alternate forms for type casting: C++ only | C\C++ type (variable) |(type) variable | ave = sum / float (n); | ave = sum / (float) n; where n is declared as int

Character Data and Functions t Character literal const char star = ‘*’; char nextLetter; nextLetter = ‘A’;

36 Character Representation t Bits required to store characters is based on the ASCII table (Appendix A) t Each character has a numeric code t 1 byte or 8 bits are typically used to represent characters

37 Relational Operators and Characters t Relational operators can be used with characters t Testing based on the characters ASCII value example:‘0’ < ‘1’ True ‘A’ < ‘B’ True

38 Arithmetic Operators and Characters t Arithmetic operators can be used with characters t Testing based on the characters ASCII value example:‘A’ - ‘a’ results to -32 ‘a’ - ‘A’ results to 32

39 Character Functions t and libraries provide many functions to the programmer t Table on next slide lists many of the functions char tolower(char c) if c is uppercase, this function returns the corresponding lower case letter

40 Character Functions – char toupper(char) – bool isalnum(char) – bool isalpha(char) – bool isdigit(char) – bool isxdigit(char) – bool isspace(char) – bool iscntrl(char) t etc

41 ASCII table visualized – ver 1 #include using namespace std; void main () { const int MIN = 32;const int MAX = 126;char nextChar; // Display sequence of characters. for (int nextCode = MIN; nextCode <= MAX; nextCode++) { nextChar = char (nextCode); cout << nextChar; if (nextChar == 'Z') cout << endl; }

42 ASCII table visualized – ver 1 Program Output Program output … !”#$%&`()*+,./ ;: ? ABCDEFGHIJKLMNOPQRSTUVWXYZ [/]^_’abcdefghijklmnopqrstuvwxyz{|}~.

43 ASCII table visualized – ver 2 ASCII table Ddistribution of numeric codes zones: 0-31control characters 48-57decimal digits 65-90capital letters lower case letters

44 ASCII table visualized – ver 2 #include using namespace std; void main () { // Each character has a numeric code. Display // characters as symbol and in dec, hex, oct format. // display numeric codes for decimal digits ‘0’.. ‘9’ for (int ch = 48; ch <= 57; ch++) { cout << endl << (char)ch << “ “ << dec << ch << “ “ << hex << ch << “ “ << oct << ch; }

45 ASCII table visualized – ver 2 #include using namespace std; void main () { // Each character has a numeric code. Display // characters as symbol and in dec, hex, oct format. // display numeric codes for capital letters ‘A’ … ‘Z’ for (int ch = 65; ch <= 90; ch++) { cout << endl << (char)ch << “ “ << dec << ch << “ “ << hex << ch << “ “ << oct << ch; }

46 ASCII table visualized – ver 2 #include using namespace std; void main () { // Each character has a numeric code. Display // characters as symbol and in dec, hex, oct format. // display numeric codes for lower case letters ‘a’…‘z’ for (int ch = 97; ch <= 122; ch++) { cout << endl << (char)ch << “ “ << dec << ch << “ “ << hex << ch << “ “ << oct << ch; }

47 ASCII table visualized – ver 2 #include using namespace std; void main () { // Each character has a numeric code. Display // characters as symbol and in dec, hex, oct format. // display numeric codes for control characters only for (int ch = 0; ch <= 31; ch++) { cout << endl << (char)ch << “ “ << dec << ch << “ “ << hex << ch << “ “ << oct << ch; }

48 ASCII table visualized – ver 2 #include using namespace std; void main () { // Each character has a numeric code. Display // characters as symbol and in dec, hex, oct format. // display numeric codes for half the ASCII table for (int ch = 0; ch <= 127; ch++) { cout << endl << (char)ch << “ “ << dec << ch << “ “ << hex << ch << “ “ << oct << ch; }

49 ASCII table visualized – ver 2 #include using namespace std; void main () { // Each character has a numeric code. Display // characters as symbol and in dec, hex, oct format. // display numeric codes for all the ASCII table for (int ch = 0; ch <= 255; ch++) { cout << endl << (char)ch << “ “ << dec << ch << “ “ << hex << ch << “ “ << oct << ch; }

Type bool Data and Logical Expressions t Used in assignment statements and logical expressions (True and False) t Complementing expressions <>= ><= >=< ==!= !===

51 Type bool Functions t bool function isdigit if (isdigit (ch)) cout << “You entered a number”; t bool return value from a function if (centsOverflow (cents)) { cents -= 100; dollars ++; }

52 Input and Output with bool t Can NOT be used for input or output –True represented by a numeric 1 –False represented by numeric 0 t Displaying bool values –cin.setf (ios::boolalpha); –cout.setf (ios::boolalpha);

Enumeration Types t Aid program readability t Represent various states example: enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday}; sunday has the value 0 monday has the value 1 and so on user-defined data type

54 Enumeration Type Declarations enum enumeration-type {enumerator-list}; enum classId {freshman, sophomore, junior,senior}; classId newClass; if (newClass == freshman) else if (newClass == sophomore)

55 Enumeration Types t Characters t Switch statements t Comparisons t Write functions to read and write enumerated types (not know to compiler) t Discuss color.cpp

56 color.cpp // DISPLAYS THE VALUE OF thisColor void writeColor (color thisColor) { switch (thisColor) { case red:cout << "red";break; case green:cout << "green"; break; case blue:cout << "blue";break; case yellow:cout << "yellow";break; default:cerr << "*** ERROR: Invalid color value.\n“; }

Common Programming Errors t Omitting pairs of parentheses –m = y2 - y1 / x2 - x1 –Compiler will not complain but calculation will be in error t Unbalanced parentheses –z = sqrt (x + y) / (1 + sqrt (x + y)); t Mixing operators and operand types –float == char

58 Common Programming Errors t Operator Precedence errors –Watch use of parentheses to get correct precedence –! Symbol t Enumeration types –Identifiers can only appear in list –Only use one value for each enumerated declaration

59 Exercises 19.1 – 19.5 Build programs:  To accumulate weekday hours worked.  To convert a string of digits to its numeric equivalent (own version of atoi())  To display the ASCII code character set for letters and digits in character, decimal, octal and hexadecimal format;  To convert a single character to lower case for the ASCII character set. If the character is not an upper case letter, it stays unchanged;  To convert a single character to upper case for the ASCII character set. If the character is not a lower case letter, it stays unchanged

60 Before lecture end Lecture: Simple Data Types More to read: Friedman/Koffman, Chapter 07

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Simple Data Types Problem Solving, Abstraction, and Design using C++ 5e by Frank L. Friedman and Elliot B. Koffman

62 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.1 Constants Revisited Reasons to use constants –constants are named, so easy to understand –compiler prevents accidental change in value –good programming practice for preventing errors and making code more readable General form const type identifier = constant;

63 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley #define Compiler Directive An additional way to define constants Used in older C programs prior to introduction of constants #define identifier replacement-text #define pi The same as const float pi = ;

64 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.2 Internal Representations of int and float float and int used to represent numbers Stored differently in the computer int stored as binary 1s and 0s –sign bit and value as binary number float stored in 2 parts plus the sign sign - characteristic - mantissa float-number = mantissa  2 characteristic

65 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Integer Types Three sizes of int –short int –int –long int Each uses a different amount of the computers memory –long and short provide consistency between compilers –short can save lots of memory

66 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Floating-Point Types Three sizes of float –float –double –long double Each uses a different amount of the computer’s memory –double is no less precise than float –long double provides more precision than double

67 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Types of Numeric Literals If the literal has a decimal point, it’s of type float A literal without a decimal point is an integer (type int)

68 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 7.1 Special C++ Constants

69 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Numerical Inaccuracies Can have representational errors when using float in some computations, due to the way floats are stored –some real numbers cannot be represented accurately (e.g. 1/3) –conversion from fractional decimal to binary not always precise –Depends on the number of binary bits used in the mantissa Cancellation error when combining large and small numbers Arithmetic underflow and arithmetic overflow –E.g. multiplying two small or large numbers together, respectively

70 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Mixed Types: Promotions Allowed to mix certain types in expressions, assignments, and argument passing The compiler must examine operations involved with each operation and convert (promote) mixed operands to make them all the same Integer types are promoted to floating-point types when mixed

71 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Type Conversions Conversions meant to be value preserving x = 2;// float x Truncation can occur i = 3.89;// int i ch = 64.97;// char ch printInt(27.7);// void printInt(int)

72 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Type Casting In addition to automatic conversion, can force conversion using a cast average = float(sum) / float(n); where sum and n are type int. Note: NOT average = float(sum / n);

73 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.3 Character Data and Functions char type can contain exactly one character Literal consists of character surrounded by single quotation marks. E.g. const char STAR = ‘*’; const char ENDLINE = ‘\n’; char nextLetter; nextLetter = ‘A’;

74 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Character Representation Each character has a unique numeric code The bits required to store characters is based on the ASCII table (Appendix A) 1 byte (8 bits) are typically used to represent characters (rightmost 7 bits are the code, extra bit usually ignored) Can convert between char and int types.

75 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Some Useful Character Functions char tolower(char); char toupper(char); bool isalpha(char); bool isdigit(char) bool islower(char); bool isspace(char); bool isupper(char);

76 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.2 Function digitToNumber

77 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.4 Type bool Data and Logical Expressions bool type values are true and false Complementing logical expressions can be done in 2 ways –using logical operator ! (not) –using DeMorgan’s Theorem

78 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The ! (not) Operator Useful in writing if and while conditions –can simplify the expression –can make expression more readable Complements of relational operators: <>= >=< = =!= ><= !== =

79 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley DeMorgan’s Theorem !(exp 1 && exp 2 ) is the same as exp 1 || exp 2 !(exp 1 || exp 2 ) is the same as exp 1 && exp 2

80 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Input and Output of bool Data bool data displays 0 for false and 1 for true Must enter 0 for false and 1 for true for input of bool value Don’t usually want to read/write boolean values Can enter/print false and true for bool data: cin.setf(ios::boolalpha); cout.setf(ios::boolalpha);

81 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.5 Enumeration Types Aid program readability Associates integer values with new programmer- defined values E.g.: enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday}; Enumerator sunday has the value 0, monday has the value 1, and so on

82 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Enumeration Type Declarations enum enumeration-type {enumerator-list}; enum classId {freshman, sophomore, junior, senior}; classId newClass; if (newClass == freshman) do something else if (newClass == sophomore)...

83 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparisons Involving Enumeration Types The order relationship is determined by the order of enumerators in the list sunday < monday wednesday != tuesday wednesday == wednesday thursday > monday Cannot mix enumeration types entertainment != monday

84 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Reading and Writing Enumeration Type Values Can’t read/write directly, must use own functions Consider definitions enum color {red, green, blue, yellow}; color eyeColor = blue; and function call writeColor(eyeColor);

85 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.4 Function to display a value of type color void writeColor (color thisColor) // IN: color to display as a string { // Display color value as a string. switch (thisColor) { case red: cout << “red “; break; case green: cout << “green “; break; case blue: cout << “blue “; case yellow: cout << “yellow “; break; default: cout << “*** ERROR: Invalid color value.” << endl; }

86 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.5 Function to read a value of type color

87 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Program Style Usually end switch case with a break statement For a switch in a function, may want to replace each break with a return statement

88 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Placement of Enumeration Type Declarations Normally want enumeration types to be available to multiple functions Good practice to declare enumeration types before function prototypes Doing so causes enumeration types to have global scope

89 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.6 Common Programming Errors Omitting pairs of parentheses m = y2 - y1 / x2 - x1; Compiler will not complain but calculation will be in error Unbalanced parentheses z = sqrt (x + y) / (1 + sqrt (x + y)); Incorrectly mixing operators and operand types

90 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Common Programming Errors Operator Precedence errors –Watch use of parentheses to get correct precedence –! symbol has high precedence Using enumeration types –Identifiers only must appear in list –Enumerator must appear in only one list –Don’t use quote marks around enumerators

91 Thank You For Your Attention