Download presentation
Presentation is loading. Please wait.
Published byMarshall Hunt Modified over 9 years ago
1
Lecture 19: Simple Data Types
2
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
19 More on Simple Data Types Extract from Friedman/Koffman, chapter 7
20
Simple Data Types Chapter 7
21
21 7.1 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
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 3.14159 The same as const double pi = 3.14159;
23
23 7.2 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
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
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
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
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
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 32767 /* maximum (signed) short value */ #define USHRT_MAX 0xffff /* maximum unsigned short value */ #define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */ #define INT_MAX 2147483647 /* maximum (signed) int value */ #define UINT_MAX 0xffffffff /* maximum unsigned int value */ #define LONG_MIN (-2147483647L - 1) /* minimum (signed) long value */ #define LONG_MAX 2147483647L /* maximum (signed) long value */ #define ULONG_MAX 0xffffffffUL /* maximum unsigned long value */
29
29 Extract from #define DBL_DIG 15 /* # of decimal digits of precision */ #define DBL_MAX 1.7976931348623158e+308 /* max value */ #define DBL_MIN 2.2250738585072014e-308 /* min positive value */ #define FLT_DIG 6 /* # of decimal digits of precision */ #define FLT_MAX 3.402823466e+38F /* max value */ #define FLT_MIN 1.175494351e-38F /* min positive value */
30
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
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
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
33 Mixing Types t Example: int y; float x = 3.89; y = x; y would contain 3
34
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
35
35 7.3 Character Data and Functions t Character literal const char star = ‘*’; char nextLetter; nextLetter = ‘A’;
36
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
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
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
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
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
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
42 ASCII table visualized – ver 1 Program Output Program output … !”#$%&`()*+,./0123456789;: ? ABCDEFGHIJKLMNOPQRSTUVWXYZ [/]^_’abcdefghijklmnopqrstuvwxyz{|}~.
43
43 ASCII table visualized – ver 2 ASCII table Ddistribution of numeric codes zones: 0-31control characters 48-57decimal digits 65-90capital letters 97-122lower case letters
44
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
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
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
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
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
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; }
50
50 7.4 Type bool Data and Logical Expressions t Used in assignment statements and logical expressions (True and False) t Complementing expressions <>= ><= >=< ==!= !===
51
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
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);
53
53 7.5 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
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
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
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“; }
57
57 7.6 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
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
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
60 Before lecture end Lecture: Simple Data Types More to read: Friedman/Koffman, Chapter 07
61
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
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
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 3.14159 The same as const float pi = 3.14159;
64
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
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
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
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
68 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 7.1 Special C++ Constants
69
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
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
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
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
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
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
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
76 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.2 Function digitToNumber
77
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
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
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
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
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
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
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
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
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
86 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.5 Function to read a value of type color
87
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
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
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
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
91 Thank You For Your Attention
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.