csci 6610: review [2ex]chapter 7: numbers chapter 8

27
... 1/27 CSCI 6610: Review Chapter 7: Numbers Chapter 8: Characters Chapter 11 Pointers Alice E. Fischer February 1, 2016

Upload: others

Post on 21-Mar-2022

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 1/27

CSCI 6610: Review

Chapter 7: NumbersChapter 8: CharactersChapter 11 Pointers

Alice E. Fischer

February 1, 2016

Page 2: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 2/27

Outline

The Trouble with Numbers

The char Data Types

Pointers

Page 3: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 3/27

The Trouble with Numbers

I. The Trouble with Numbers

Integer overflow and wrapFloating point overflow

Floating point underflowFloating point precision and approximate calculation

Scale of Magnitude and limits on precision

Page 4: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 4/27

The Trouble with Numbers

Integer overflow and wrap

If you keep making an integer larger, eventually it will wrap aroundto the smallest end.

Memorize these numbers if you can.

I short -32,767. . . 32,767

I unsigned short: 0. . . .65,535

I long: -2,147,483,647. . . 2,147,483,647

I unsigned long 0. . . 4,294,967,295

I Today, an int us usually the same as a long. 20 years ago, itwas the same as a short on some machines.

Page 5: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 5/27

The Trouble with Numbers

Floating-Point Numbers

I A floating point number has a sign, an exponent, and amagnitude.

I The sign is the sign of the number.

I The exponent is a positive or negative base-2 numberrepresented in bias notation. A float has a bias-127 exponent:if it starts with a 1 bit, it represents a positive exponent, if itstarts with a 0 bit, the exponent is negative.

I The magnitude is always kept normalized. After everycalculation, the result is shifted left or right, until the first bitis a 1. The exponent is adjusted for each shift.

I During normalization, 1 bits can be shifted off the end of theregister or 0 bits can be brought in.

Page 6: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 6/27

The Trouble with Numbers

Floating point precision and approximate calculation

I A float has 24 bits of magnitude, equivalent to 6+ decimaldigits of precision.

I A float can represent integers exactly, if the integer is shorterthan 24 bits and it is directly converted to type float.

I A double has 36 bits of magnitude, equivalent to 15+ decimaldigits of precision.

I A double can represent any integer exactly if it is directlyconverted to type double.

I However, most fractional values cannot be exactly representedbecause of the limited precision.

I Each time a computation is made, round-off error is possible.Over time, it adds up.

I So a double that is the result of computation is UNLIKELY toEVER exactly equal an integer.

Page 7: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 7/27

The Trouble with Numbers

Floating point overflow

I When the exponent becomes 0 or too large to represent, thevalue becomes a NaN, that is, Not a Number. Some systemsdisplay a special character for Nan, others just show anonsense value. Please learn what your system does and learnto recognize Nan.

I The exponent of a float is 8 bits, able to represent base-10exponents of ±38

I The exponent of a double is 12 bits, able to represent base-10exponents of ±308

I If the exponent of a number grows beyond that, the numberbecomes a NaN.

I Any arithmetic done on a NaN gives the result NaN.

Page 8: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 8/27

The Trouble with Numbers

Floating point underflow

Suppose, during a calculation, an exponent has been adjusted sothat it is at the limit but the magnitude is STILL not normalized.

I At that point, the limited precision of the float or double isdecreased.

I Some systems will let you continue to use that unnormalizednumber.

I Others will not.

Page 9: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 9/27

The Trouble with Numbers

Fuzzy Comparisons

I Because the value of a float or double is usually not accuratein its last few bits, we never use == to compare anything tothe result of a floating computation.

I The method of comparison must include a fuzz factor.if ( fabs( answer - target )< fuzz ) // end loop.

I fabs() is floating point absolute value.

I fuzz is a float or double constant such as .0001 that isappropriate for the amount of precision that you need.

Page 10: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 10/27

The Trouble with Numbers

Scale of Magnitude and limits on precision

When two floating values are added together,

I If they have the same exponents, they are just added andrenormalized.

I If the exponent is different, the smaller exponent must beadjusted by DE-normalizing the number. Then themagnitudes are added and the result is re-normalized.

I In the process of de-normalization, all of the information inthe smaller number can get shifted off the end and lost,leaving a 0 value.

I This happens when the exponents differ by too much.

Page 11: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 11/27

The char Data Types

II. The char Data Types

Page 12: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 12/27

The char Data Types

A dual-purpose type

A char is a dual-purpose data type:

I Representing characters like ’A’ and ’z’ and ’5’ and ’}’.

I Representing very small integers. Note: ’5’ != 5.

Note that single quotes are used for character literals, and doublequotes for strings. ’A’ is a char and "A" is a string and "This is

a string".

There are two char types: signed char, and unsigned char.Type char is the same as one or the other, whichever is native onyour hardware / OS.

Page 13: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 13/27

The char Data Types

Signed and unsigned chars

Like other integer types, chars can be either signed or unsigned.

I Some operating systems use signed chars for characters,others use unsigned chars.

I Most of the time you don’t know and you don’t need to know.

I ASCII code can be stored in a signed char, since it is a 7-bitcode, the sign bit is not important.

I International ASCII is an 8-bit code and requires unsignedchar.

I Modern systems are moving to Unicode, a 16-bit characterrepresentation.

Page 14: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 14/27

The char Data Types

Operations on chars

You can do some kinds of computations with characters.Copy them: (ch = ’A’)

Compare them: if (ch == ’A’ ‖ ch ==’a’)

Add an integer: nextLetter = ch + 1

Subtract a char to get an int: position = ch - ’A’;

Use as a subscript: counter[ch]++

Use in a switch: switch( ch ) {

case ’A’:. . .

Page 15: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 15/27

The char Data Types

Reading and Writing Characters in C

I Use " %c" to read a character. Note the space between thequote and the percent. This skips leading whitespace, thenreads a single keystroke.

I Use "%c" to read the next keystroke WITHOUT skippingwhitespace.

I Use "%c" to write a character.

I Use "%i" to read a small integer into a char variable. Thiscould read a number with more than one keystroke. It doesascii to integer conversion.

I Use "%s" to read a to read a whitespace-delimited string.

Note: Using " %c" is the right way to eliminate whitespace at theend of a line when the next line starts with a char.

Page 16: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 16/27

The char Data Types

Two Examples

char ch1, ch2 = ’\n’;

printf( "Please guess my secret character: " );

scanf( "%c", ch1 ); // Read the next keystroke.

printf( "Guess is %c, my secret is %c\n", ch1, ch2 );

printf( "Who was the first U.S. President?" );

printf( "W: Washington, A: Adams, J: Jefferson" );

scanf( " %c", &ch1 ); // Read one visible char.

if( response == ’W’ ) puts "Right; good job.");

else puts( "Wrong, try again.");

Page 17: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 17/27

The char Data Types

Reading and Writing Characters in C++

I Use cin >> ch; to read a character. This skips leadingwhitespace, then reads a single keystroke.

I Use ch = cin.get() to read the next keystroke WITHOUTskipping whitespace.

I Use cout << ch; to write a character.

I Use cin >> str; to read a whitespace-delimited string.

Page 18: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 18/27

The char Data Types

Two Examples in C++

char ch1, ch2 = ’@’;

cout <<"Please guess my secret character: ";

ch1 = cin.get(); // Read the next keystroke.

cout <<"Guess is " << ch1

<<" my secret is " <<ch2 << ".\n";

cout <<"Who was the first U.S. President?\n"

<<"W: Washington, A: Adams, J: Jefferson" <<endl;

cin >> ch1; // Read one visible char.

if( response == ’W’ ) cout <<"Right; good job.\n";

else cout <<"Wrong, try again.\n";

Page 19: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 19/27

The char Data Types

The ctype library: Character Processing Functions

The ctype library contains functions for processing character data.

These can be used either in C or in C++:isalpha(ch) true for A. . . Z and a. . . z, false otherwiseisdigit(ch) true for 0. . . 9, false otherwiseisalnum(ch) same as isalpha() ‖ isdigit()

isspace(ch) true for a whitspace character, false otherwise(space, tab, newline, CR, vertical tab or formfeed)

islower(ch) true for a. . . z, false otherwiseisupper(ch) true for A. . . Z, false otherwisetolower(ch) If ch is A. . . Z, return a. . . z. Else return ch unchanged.toupper(ch) If ch is a. . . z, return A. . . Z. Else return ch unchanged.

Page 20: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 20/27

Pointers

III. PointersDiagrams of pointers

Pointer operations

Page 21: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 21/27

Pointers

Pointer Details

I A pointer is an address. We say it has star-level 1.

I An int has star-level 0. The address of an int has level 1.

I A pointer variable is a variable that stores an address.

I Pointers are used to process arrays. An array has star-level 1

I Pointers are used to return answers from functions.

int k = 5;

int ary[4] = {}; // An array: 4 slots initialized to 0

int* p1 = &k; // Star-level must match.

int* p2 = arr;

int* p3 = &arr[0]; // Same as line above.

int* q = nullptr; // In C, use NULL.

Page 22: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 22/27

Pointers

int k = 5; int ary[4] = {}; int* p1 = &k; int* p2= arr; int* q = nullptr

arr [0] [1] [2] [[3]

0 0 0 0k 5

p1

p2q

Page 23: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 23/27

Pointers

Pointer Semantics

I The name of an array is translated as a pointer to its slot 0.

I The slot 0 of an array is guaranteed to be at a lower addressthan slot 1.

I The following things make sense ONLY if pointers p and q arepointing into the same array. Pointer arithmetic works in unitsof array slots, not bytes.

I Point to the first byte that is NOT in the array.I Add int N to p to move p N slots toward end of the array.I Subtract q-p to find the # of array slots between p and qI Compare p==q to find if they point to the same array slotI Compare p > q to learn which one is at a larger subscript

Page 24: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 24/27

Pointers

Pointer Semantics and Usage

I In the declaration, the * is part of the type, not part of thevariable name.

I In the code, *p means the contents of the variable p points at.

I In the code, p means the address that p points at.

I So p1 = p2 changes the address that p1 points at.

I So *p1 = *p2 changes something in the underlying array.

p1 = arr; // Point at head of the array.

p2 = arr+4; // Point at the first non-array slot.

q = p1; // q and p1 point at the same thing.

for (q=p1; q<p2; ++q). . . // process the whole array.

Page 25: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 25/27

Pointers

p1 = arr; // This is a stationary head pointer.p2 = arr+4; // This is an offboard tail pointer. q = p1; // This is a scanning pointer. for (q=p1; q<p2; ++q). . .

arr [0] [1] [2] [[3]

0 0 0 0p1

p2q

?

Page 26: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 26/27

Pointers

Array Parameters

I An array argument is ALWAYS passed by pointer. This savestime and space.

I In the function call, use the array name, without any & orsubscript.

I In the function, declare the parameter to be a pointer or anarray; it makes little difference.

I Inside the function, you can use subscripts, even if theparameter is a * type.

I The length of the array is NOT passed to the function as partof the array, so it must be passed separately.

Page 27: CSCI 6610: Review [2ex]Chapter 7: Numbers Chapter 8

. . . 27/27

Pointers

Pointer Parameters

I A pointer parameter can be used to return an answer from afunction.

I For example, to return a double, you might declare theparameter to be double* db.

I Inside the code, near the end, you would write*db = answer;