lecture 19: simple data types. 2 lecture contents: t representation and conversion of numeric types...

91
Lecture 19: Simple Data Types

Upload: marshall-hunt

Post on 30-Dec-2015

226 views

Category:

Documents


1 download

TRANSCRIPT

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

Lecture 19:Simple Data Types

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

2

Lecture Contents:

Representation and conversion of numeric types Representation and conversion of type char Enumerated types Demo programs Exercises

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

3

Basic topics

Classification of Data Types:

/ \Standard (predefined) Abstract: user defined

bool, enumerated

char, abstract UDT - OOP

int, short, long, unsigned,

float, double

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

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.

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

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.

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

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;

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

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;

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

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;

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

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<int>(6.778); // explicit conversion

cout << a << endl; cout << b << endl; cout << c << endl; cout << d << endl;

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

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;

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

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;

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

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

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

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;

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

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;

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

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 <= Sun; static_cast<weekday>(day+1)) cout << endl << day;

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

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;

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

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!

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

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

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

19

More on Simple Data Types

Extract from Friedman/Koffman, chapter 7

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

Simple Data Types

Chapter 7

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

21

7.1 Constants Revisited

Three reasons to use constants– Constant is recognizable– Compiler prevents changes in value– Programming practices

const type identifier = constant;

const int FileSize = 4096;

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

22

#define

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 double pi = 3.14159;

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

23

7.2 Internal Representations of int and float

float, double and int used to represent numbers

Stored differently in the computer memory int stored as binary 1s and 0s

– sign and binary number float, double stored in 2 parts plus the sign

– sign - characteristic - mantissa– Value of float number = mantissa * 2characteristic

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

24

Value Variations

Three sizes of integer data type– 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

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

25

Value Variations

Three sizes of real data type– float– double– long double

Each uses a different amount of the computers memory– double is no less precise than float– long double provides less?? precision than double

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

26

Numerical Inaccuracies

Can have errors when using float in some computations

Do to the way floats are stored Errors will be determined by the number of binary

bits used in the mantissa Arithmetic underflow and arithmetic overflow

– Multiplying 2 small or 2 large numbers together respectively

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

27

Ranges for int and float Constants

See tables on next two slides Definitions for some of these C++ constants

are in the <climits>, <limits.h> and

<cfloat>, <float.h> libraries The actual values of these constants will

vary from computer to computer

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

28

Extract from <climits>

#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 */

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

29

Extract from <cfloat>

#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 */

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

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;

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

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;

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

32

Mixing Types

The notion of type promotion– promoting a lower type to a higher typeexample: 3 + x /2 – if x is float, constant 2 would be promoted to

float as well and actually be 2.0 Type conversions

– int to float (number.0)– float to int (truncation occurs)

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

33

Mixing Types

Example:

int y;

float x = 3.89;

y = x;

y would contain 3

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

34

Type Casting

Avoid mixing types but if you need to,you can cast a type

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

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

35

7.3 Character Data and Functions

Character literal

const char star = ‘*’;

char nextLetter;

nextLetter = ‘A’;

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

36

Character Representation

Bits required to store characters is based on the ASCII table (Appendix A)

Each character has a numeric code 1 byte or 8 bits are typically used to

represent characters

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

37

Relational Operators and Characters

Relational operators can be used with characters

Testing based on the characters ASCII value

example: ‘0’ < ‘1’ True

‘A’ < ‘B’ True

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

38

Arithmetic Operators and Characters

Arithmetic operators can be used with characters

Testing based on the characters ASCII value

example: ‘A’ - ‘a’ results to -32

‘a’ - ‘A’ results to 32

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

39

Character Functions

<cctype> and <ctype.h> libraries provide many functions to the programmer

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

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

40

Character Functions

– char toupper(char)– bool isalnum(char)– bool isalpha(char)– bool isdigit(char)– bool isxdigit(char)– bool isspace(char)– bool iscntrl(char)

etc

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

41

ASCII table visualized – ver 1

#include <iostream>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; }}

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

42

ASCII table visualized – ver 1

Program Output

Program output …

!”#$%&`()*+,./0123456789;:<=>?

ABCDEFGHIJKLMNOPQRSTUVWXYZ

[/]^_’abcdefghijklmnopqrstuvwxyz{|}~.

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

43

ASCII table visualized – ver 2

ASCII table

Ddistribution of numeric codes zones:

0-31 control characters

48-57 decimal digits

65-90 capital letters

97-122 lower case letters

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

44

ASCII table visualized – ver 2

#include <iostream>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; }}

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

45

ASCII table visualized – ver 2

#include <iostream>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; }}

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

46

ASCII table visualized – ver 2

#include <iostream>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; }}

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

47

ASCII table visualized – ver 2

#include <iostream>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 onlyfor (int ch = 0; ch <= 31; ch++) { cout << endl << (char)ch << “ “ << dec << ch << “ “ << hex << ch << “ “ << oct << ch; }}

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

48

ASCII table visualized – ver 2

#include <iostream>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 tablefor (int ch = 0; ch <= 127; ch++) { cout << endl << (char)ch << “ “ << dec << ch << “ “ << hex << ch << “ “ << oct << ch; }}

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

49

ASCII table visualized – ver 2

#include <iostream>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 tablefor (int ch = 0; ch <= 255; ch++) { cout << endl << (char)ch << “ “ << dec << ch << “ “ << hex << ch << “ “ << oct << ch; }}

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

50

7.4 Type bool Data and Logical Expressions

Used in assignment statements and logical expressions (True and False)

Complementing expressions< >=

<= >

> <=

>= <

== !=

!= ==

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

51

Type bool Functions

bool function isdigitif (isdigit (ch))

cout << “You entered a number”;

bool return value from a functionif (centsOverflow (cents))

{

cents -= 100;

dollars ++;

}

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

52

Input and Output with bool

Can NOT be used for input or output– True represented by a numeric 1– False represented by numeric 0

Displaying bool values– cin.setf (ios::boolalpha);– cout.setf (ios::boolalpha);

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

53

7.5 Enumeration Types

Aid program readability Represent various statesexample:

enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};

sunday has the value 0monday has the value 1 and so on

user-defined data type

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

54

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)<do something else>

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

55

Enumeration Types

Characters Switch statements Comparisons Write functions to read and write

enumerated types (not know to compiler) Discuss color.cpp

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

56

color.cpp

// DISPLAYS THE VALUE OF thisColorvoid 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“; }}

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

57

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)); Mixing operators and operand types

– float == char

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

58

Common Programming Errors

Operator Precedence errors– Watch use of parentheses to get correct

precedence– ! Symbol

Enumeration types– Identifiers can only appear in list– Only use one value for each enumerated

declaration

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

59

Exercises 19.1 – 19.5Build 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

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

60

Before lecture end

Lecture:

Simple Data Types

More to read:

Friedman/Koffman, Chapter 07

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

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

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

62Copyright © 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;

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

63Copyright © 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;

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

64Copyright © 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 signsign - characteristic - mantissa

float-number = mantissa 2characteristic

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

65Copyright © 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

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

66Copyright © 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

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

67Copyright © 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)

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

68Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table 7.1 Special C++ Constants

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

69Copyright © 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

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

70Copyright © 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

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

71Copyright © 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)

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

72Copyright © 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);

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

73Copyright © 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’;

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

74Copyright © 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.

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

75Copyright © 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);

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

76Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 7.2 Function digitToNumber

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

77Copyright © 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

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

78Copyright © 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:

< >= >= <

<= > = = !=

> <= != = =

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

79Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

DeMorgan’s Theorem

!(exp1 && exp2)

is the same as

exp1 || exp2

!(exp1 || exp2)

is the same as

exp1 && exp2

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

80Copyright © 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);

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

81Copyright © 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

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

82Copyright © 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). . .

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

83Copyright © 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

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

84Copyright © 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);

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

85Copyright © 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;

}}

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

86Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 7.5 Function to read a value of type color

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

87Copyright © 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

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

88Copyright © 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

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

89Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7.6 Common Programming Errors

• Omitting pairs of parenthesesm = y2 - y1 / x2 - x1;

Compiler will not complain but calculation will be in error

• Unbalanced parenthesesz = sqrt (x + y) / (1 + sqrt (x + y));

• Incorrectly mixing operators and operand types

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

90Copyright © 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

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

91

Thank You

For

Your Attention