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

Preview:

Citation preview

Lecture 19:Simple Data Types

2

Lecture Contents:

Representation and conversion of numeric types Representation and conversion of type char Enumerated types Demo programs 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<int>(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 <= Sun; static_cast<weekday>(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

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;

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;

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

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

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

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

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

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

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

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

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)

33

Mixing Types

Example:

int y;

float x = 3.89;

y = x;

y would contain 3

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

35

7.3 Character Data and Functions

Character literal

const char star = ‘*’;

char nextLetter;

nextLetter = ‘A’;

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

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

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

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

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

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

42

ASCII table visualized – ver 1

Program Output

Program output …

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

ABCDEFGHIJKLMNOPQRSTUVWXYZ

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

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

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

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

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

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

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

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

50

7.4 Type bool Data and Logical Expressions

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

Complementing expressions< >=

<= >

> <=

>= <

== !=

!= ==

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

}

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

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

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>

55

Enumeration Types

Characters Switch statements Comparisons Write functions to read and write

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

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“; }}

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

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

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

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

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;

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;

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

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

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

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)

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

Table 7.1 Special C++ Constants

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

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

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)

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

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

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.

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

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

Listing 7.2 Function digitToNumber

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

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:

< >= >= <

<= > = = !=

> <= != = =

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

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

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

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

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

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

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;

}}

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

Listing 7.5 Function to read a value of type color

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

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

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

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

91

Thank You

For

Your Attention

Recommended