thicks/1320/handouts/aabout... · web viewword[10]; the last character in every string is an...

42
INTEGERS Minimal ANSI Limits –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– ––––––––––––––––– min const minimum value data type maximum value #bytes –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– ––––––––––––––––– short int -128 <= short int <= +127 1 int -32,768 <= int <= +32,767 2 long int -2,147,483,648 <= long int <= +2,147,483,647 4 –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– ––––––––––––––––– min const minimum value data type maximum value #bytes –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– ––––––––––––––––– unsigned short int 0 <= unsigned short int <= +255 1 unsigned int 0 <= unsigned int <= +65,535 2 unsigned long int 0 <= unsigned long int <= +4,294,967,295 4 –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– ––––––––––––––––– Integer Format Specifiers –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– –––––––––––– Data Type Format Specifier Right Justify 8 Characters Left Justify 8 Characters –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– –––––––––––– short int %h or %hi %8h or %8hi %–8h or %–8hi int %d or %i %8d or %8i %–8d or %–8i long int %ld or %li %8ld or %8li %–8ld or %–8li

Upload: vannga

Post on 06-May-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

INTEGERS

Minimal ANSI Limits––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– min const minimum value data type maximum value #bytes –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––short int -128 <= short int <= +127 1int -32,768 <= int <= +32,767 2 long int -2,147,483,648 <= long int <= +2,147,483,647 4–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

min const minimum value data type maximum value #bytes –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––unsigned short int 0 <= unsigned short int <= +255 1unsigned int 0 <= unsigned int <= +65,535 2 unsigned long int 0 <= unsigned long int <= +4,294,967,295 4–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

Integer Format Specifiers

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––Data Type Format Specifier Right Justify 8 Characters Left Justify 8 Characters––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––short int %h or %hi %8h or %8hi %–8h or %–8hiint %d or %i %8d or %8i %–8d or %–8ilong int %ld or %li %8ld or %8li %–8ld or %–8li

unsigned short int %hu %8hu %–8huunsigned int %u %8u %–8uunsigned long int %lu %8lu %–8lu––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

%5d or %5i used to right justify (5 character) int%7ld or %7li used to right justify (7 character) long int%3h or %3hi used to right justify (3 character) short int%12u used to right justify (12 character) unsigned int%8lu used to right justify (8 character) long unsigned int%4hu used to right justify (4 character) short unsigned int%-5d or %-5i used to left justify (5 character) int%-7ld or %-7li used to left justify (7 character) long int%-3h or %-3hi used to left justify (3 character) short int

%o or %O used for Octal Notation%x or %X used for Hexadecimal Notation

The format control string may also include any of the following escape sequences: (note that the escape sequences begin with the \ and alter the flow of printing for special events)

Page 2: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[2]

\n (newline) to move the cursor to the first position of the next line\r (return) to move the cursor to the first position of the line\f (formfeed) to move the cursor to the first position of the first line

of the next page (often clears console screen)\t (horiz tab) to move the cursor to the next horizontal tab position

of the current line\b (backspace) to move the cursor one position to the left \a (alert) to produce a visible or audible alert

\\ to print the backslash\" to print the double quote\' to print the single quote\? to print the question mark\07 to ring the bell

PROGRAMIntOut.c

# include <stdio.h> # define MAX 3333# define MAX 3

main() {int No;

No = 2371;printf ("Example 1 : *%d*\n",2371); printf ("Example 2 : *%2d*\n",MAX); printf ("Example 3 : *%4d*\n",2371); printf ("Example 4 : *%7d*\n",2371); printf ("Example 5 : *%-7d*\n",No); printf ("Example 6 : *%-2d*\n",2371); printf ("Example 7 : *%d%d%d*\n",1,2,3); printf ("Example 8 : *%d%d%d*\n",1,-2,3); printf ("Example 9 : *%d %d %d*\n",1,2,3); printf ("Example 10: *%2d %2d*\n",123,2371); printf ("Each int declared allocates %lu bytes\n",sizeof (int));printf ("The amount of space allocated for variable No is %lu bytes\n",

sizeof (No));printf ("The amount of space allocated constant MAX is %lu bytes\n",sizeof (MAX));printf ("The amount of space allocated constant MIN is %lu bytes\n",sizeof (MIN));return (0);

}

Output from program IntOut.c is as follows:

Example 1 : *2371*Example 2 : *3333*Example 3 : *2371*Example 4 : * 2371*Example 5 : *2371 *Example 6 : *2371*

Page 3: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[3]

Example 7 : *123*Example 8 : *1-23*Example 9 : *1 2 3*Example 10: *123 2371*Each int declared allocates 2 bytesThe amount of space allocated for variable No is 2 bytesThe amount of space allocated constant MAX is 2 bytesThe amount of space allocated constant MIN is 2 bytes

CHARACTERSThe amount of memory necessary to store a character (char) on most computers is one byte (8 bits). Before we look

at functions manipulating characters, we need to examine the way in which character data are stored. In the char data type, each character is associated with an integer. The particular sequence used by a machine for this purpose is referred to as the collating sequence for that character set. Two such sequences currently in use are

1. American Standard Code for Information Interchange (ASCII) 2. Extended Binary Coded Decimal Interchange Code (EBCDIC).

charCh, B;

Ch = 'A'; /* The Number stored in Ch = 65 (See Appendix 4) */Ch = 'B'; /* The Number stored in Ch = 66 (See Appendix 4) */B = 'C'; /* The Number stored in B = 67 (See Appendix 4) */Ch = B; /* The Number stored in Ch is same as B =67 */ B = Ch = '0'; /* The Number stored in Ch & B = 48 */Ch = 65; /* Same as Ch = 'A' */B = 65; /* Same as B = 'A' */

The putchar function will also display a character without requiring a format specifier; either of the following lines of code use function putchar to display the character A at the current cursor location.

putchar('A');putchar (65); /* Numeric ASCII 65 is character A */

PROGRAMCharOut.c# include <stdio.h> # define NON_CAP_A 'a'

main() {char

Letter;

Letter = 'B';putchar('A');putchar('B');putchar('\n');printf("%c",'H');

Page 4: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[4]

printf("%c%c%c%c\n",NON_CAP_A,'p','p','y');putchar('\n');putchar(Letter);putchar(89); putchar(69);putchar(32); putchar(33);putchar('\n');printf ("The amount of space allocated for char is %lu bytes\n",sizeof (char));printf ("The amount of space allocated for variable Letter is %lu bytes\n",

sizeof (Letter));printf ("The amount of space allocated for constant NON_CAP_A is %lu bytes\n",

sizeof (NON_CAP_A));return (0);

}

Output from CharOut.c is as follows:

ABHappy

BYE !The amount of space allocated for char is 1 bytesThe amount of space allocated for variable Letter is 1 bytesThe amount of space allocated for constant NON_CAP_A is 2 bytes

CHARACTER STRINGSA string is a collection of characters. String constants are defined with # define preprocessing statements. The entire string must be enclosed in double quotation marks(").

# define FIRST_NAME "Tom"

The string is not really a standard C data type. Students with experience in BASIC usually expect the equivalent of a string variable for storing names, and other information. Standard C does not have such a feature. However, an analogous feature, arrays of characters, is presented in chapter 7. Let us briefly examine character strings. Let us declare a string variable, called Word, that is capable of holding up to 9 letters.

charWord[10];

The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string capable of holding 10 characters (9 valid characters + end-of-string marker)In accordance with the assignment statement statement, one might guess that the character string "Worthy" could be placed into string variable Word with

Word = "Worthy"; /* Does Not Work! */

As you might gather from the comment, this does not work. C does provide a collection of string related functions in <string.h>. The call to function strcpy (below) places the string "Worthy" and the end-of-string marker into string variable Word. (See chapter 7 for additional examples.)

# include <string.h>strcpy (Word,"Worthy"); /* Word = "Worthy"; Does Not Work! */

Page 5: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[5]

It will be the computer scientist's responsibility to make sure that the string variable has been declared sufficiently large. In order to hold the string "Once Upon A Time" , the variable would have to be declared 17 characters (or more). If function strcpy were used to place the string "Once Upon A Time" into the 10 character variable Word, overflow problems will occur. This is explained in depth in chapter 7.

Formatted String Output

Output of char or strings of char can be controlled by formatting similarly to formatted character output. Within a printf, the format of the single character string is specified by a control string. The format control string could include any of the following format specifiers for string constants and variables:

%s used to format strings of char

%10s used to format string – left justify 10 characters%–10s used to format string – right justify 10 characters

As with integers, if a string field width is specified that is too small, ANSI C will print all of the characters in the string.

The following lines of code will display strings:

printf ("%s",Word);printf ("%s",FIRST_NAME);printf ("%s","The End");

The puts function will display the strings without requiring a format specifier; the puts function displays the string at the current cursor position of the standard output device (monitor) and then shifts down to the first character of the next line (newline).

puts (Word);puts ("That's All Folks!");

See program StrOut.c for examples of formatted character string output. Be sure to # include <stdio.h> when using functions printf, fprintf, sprintf, and/or puts. Be sure to #include <string.h> when using function strcpy.PROGRAMStrOut.c# include <stdio.h> # include <string.h> # define FIRST "Tom"# define LAST "Terriffic"

main() {char

Word[10];

strcpy (Word,"Batman");printf("%s\n","-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");printf(" %s\n","Good Stuff");printf("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n\n");puts("This is");puts ("a set of two lines!");printf("%s\n","-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");

Page 6: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[6]

printf ("%s%s\n",FIRST,LAST);printf("%s\n","-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");printf ("%s","Mickey");printf ("%s","Mouse");printf ("\n"); printf ("%s","Donald");printf ("%s","Duck\n");puts (Word);printf("%s\n","-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");printf("*%10s*\n","abcde");printf("*%-10s*\n","abcde");printf("*%10s*\n","abcdefghijklmnopqrstuvwxyz");printf("The ASCI value for %c = %d\n",'A','A');printf("The ASCI value for %c = %d\n\n",66,66);printf ("The amount of space allocated for char[10] is %lu bytes\n",

sizeof (char[10]));printf ("The amount of space allocated for variable Word is %lu bytes\n",

sizeof (Word));printf ("The amount of space allocated for constant FIRST is %lu bytes\n",

sizeof (FIRST));printf ("The amount of space allocated for constant LAST is %lu bytes\n",

sizeof (LAST));return (0);

}

Output from StrOut.c is as follows:

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Good Stuff-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

This isa set of two lines!-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-TomTerriffic-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-MickeyMouseDonaldDuckBatman-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* abcde**abcde **abcdefghijklmnopqrstuvwxyz*The ASCI value for A = 65The ASCI value for B = 66

The amount of space allocated for char[10] is 10 bytesThe amount of space allocated for variable Word is 10 bytesThe amount of space allocated for constant FIRST is 4 bytesThe amount of space allocated for constant LAST is 10 bytes

Floating Point Data Type

It is now time to look at numbers of type float which are real numbers. Float numbers may be written in either fixed-point decimal form or exponential form.

Page 7: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[7]

Some rules that must be observed when using fixed-point decimal floats are

1. Plus ''+'' signs, while permitted, do not have to be written before a positive float.

2. Minus ''–'' signs must be written when using a negative number.3. A decimal point and at least one digit must be included to avoid conversion;

the digit may be on either side of the decimal point.4. Commas cannot be used when writing floats. 1,362.62 is not allowed; it must

be written as 1362.625. Leading zeros in front of the decimal point are ignored. 0023.44 and 23.44

have the same value.6. Trailing zeros after the decimal point are ignored. 23.4400 and 23.44 have

the same value.

The syntax diagram for fixed-point decimal floats is

All floats seen thus far have been in fixed–point form. The computer will also accept floats in floating–point or exponential form. Floating–point form is an equivalent method for writing numbers in scientific notation to accommodate numbers that may have very large or very small values.

Some rules that must be observed when using floating-point decimal floats are

1. Plus ''+'' signs, while permitted, do not have to be written before a positive float.

2. Minus ''–'' signs must be written when using a negative number.3. A decimal point and at least one digit must be included to the left of the E to

avoid conversion; the digit may be on either side of the decimal point.4. Commas cannot be used when writing floats. 1,234.66E5 is not allowed; it

must be written as 1234.66E55. Leading zeros in front of the decimal point are ignored. 002.6E7 and 2.6E7

have the same value.6. Trailing zeros after the decimal point are ignored. 2.600E7 and 2.6E7 have

the same value.7. The real number on the left side of the E does not have to be in scientific

notation form. It may have more than one digit to the right of the decimal point.

The syntax diagram for fixed-point decimal floats is

The difference is, instead of writing the base decimal times some power of 10, the base decimal is followed by E (or e) and the appropriate power of 10. For example, 231.6 in scientific notation would be 2.316 x10and in floating–point form would be 2.316E2.

Table 2.4 sets forth several fixed–point decimal numbers with the equivalent scientific notation and floating–point form.

TABLE 2.4Forms for EquivalentNumbers

–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––Fixed–Point Scientific Notation Floating Point–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––46.345 4.6345x10 4.6345E159214.3 5.92143x10 5.92143E4

Page 8: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[8]

0.00042 4.2x10 4.2E–436000000000 3.6x10 3.6E100.000000005 5.0x10 5.0E–9–341000.0 3.41x10 3.41E5–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

TABLE 2.5Precision

–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––Data Type ANSI Precision Minimum # Bytes–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––float at least 6 digits 4double at least 12 digits 8long double at least 12 digits 8––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– The precision for float, double, and long double may also be expanded beyond the minimum. Information related to these limits may be found in the ANSI standards and <float.h>. Program FltLimit.c could be used to determine the number of bytes required to store a float, a double, and a long double on your system. For purposes of discussion in the remainder of the book, we will assume that all float are 4 bytes and all double are 12 bytes.

PROGRAM FltLimit.c

# include <stdio.h> # include <float.h>

main() {floatf;

doubled;

long doubleld;

printf ("Each float declared allocates %lu bytes\n",sizeof (f));printf ("Each double declared allocates %lu bytes\n",sizeof (d));printf ("Each long double declared allocates %lu bytes\n",sizeof (ld));return (0);

}

Output from program FltLimit.c is as follows:

Each float declared allocates 4 bytesEach double declared allocates 12 bytesEach long double declared allocates 12 bytes

Formatted Floating Point Ouptut

Output of float can be controlled by formatting similarly to formatted integer output. Note the format specifier information for fixed point in Table 2.6 and floating point in Table 2.7.

TABLE 2.6Fixed Point

–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

Total(8) Number Characters Total(8) Number CharactersData Type Format Specifier To Print - Left Justify To Print - Right Justify–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

Page 9: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[9]

float %f %8.2f %–8.2fdouble %f %8.2f %–8.2f long double %f %8.2f %–8.2f–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

TABLE 2.7FLoating Point

–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

Total(8) Number Characters Total(8) Number CharactersData Type Format Specifier To Print - Left Justify To Print - Right Justify–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––float %e or %E %12e %12E %-12e %-12Edouble %g or %G %12g %12G %-12g %-12Glong double %lg or %LG %12lg %12LG %-12lg %-12LG–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

The optional field width of the format specifier is the number that immediately follows the % sign. The negative sign and decimal point both count as one of the characters in the field width. The E counts as one of the characters in the field width for floating point form. If the format specifier field width is too small to print the entire float (including the negative sign if necessary and the decimal point), the field width is ignored and the entire number is printed. The format control string could include any of the escape sequences as those for integers.

Program FloatOut.c could be used to display the specific information about the limits of your computer/compiler combination.

PROGRAM FloatOut.c

# include <stdio.h> # include <float.h># define PI 3.14

main() {float f;

double d;

long double ld;

printf ("Example 1 : *%f*\n", 23.14); printf ("Example 2 : *%f*\n", 237.148956874); printf ("Example 3 : *%e*\n", 237.148956874); printf ("Example 4 : *%E*\n", 237.148956874); printf ("Example 5 : *%4.3f*\n", 237.148956874);printf ("Example 6 : *%16.10f*\n", 237.148956874); printf ("Example 7 : *%-16.10f*\n", 237.148956874); printf ("Example 8 : *%f*--*%f*\n",10.2,3.44); printf ("Example 9 : *%f*--*%f*\n",10.2,.44); printf ("Example 10: *%4.2f*--*%4.2f*\n",2.67,1.49); printf ("Example 11: *%4.2f*--*%4.2f*\n",162.67,208.49); printf ("Example 12: *%7.2f*\n",1.234E2);

Page 10: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[10]

f=1234.12;d=1234.12;ld=1234.12;printf ("Example 13: *%f*--*%E*\n",f,f);printf ("Example 14: *%f*--*%E*\n",d,d);printf ("Example 15: *%f*--*%E*\n",ld,ld);f=123456.12345;d=123456.12345;ld=123456.12345;printf ("Example 16: *%f*--*%E*\n",f,f);printf ("Example 17: *%f*--*%E*\n",d,d);printf ("Example 18: *%f*--*%E*\n",ld,ld);f=123456789.123456789;d=123456789.123456789;ld=123456789.123456789;printf ("Example 19: *%25.15f*--*%25.15E*\n",f,f);printf ("Example 20: *%25.15f*--*%25.15E*\n",d,d);printf ("Example 21: *%25.15f*--*%25.15E*\n",ld,ld);f=12345678912345.123456789;d=12345678912345.123456789;ld=12345678912345.123456789;printf ("Example 22: *%23.7f*--*%12e*--*%12E*\n",f,f,f);printf ("Example 23: *%23.7f*--*%12g*--*%12G*\n",d,d,d);printf ("Example 24: *%23.7f*--*%12lg*--*%12LG*\n",ld,ld,ld);f=d=ld=5.2e37;printf("Example 25: *%15.4e*\n",2.3e2);printf("Example 26: %e %e %e\n\n",f,d,ld);printf ("The amount of space allocated for float is %lu bytes\n",sizeof (float));printf ("The amount of space allocated for variable a is %lu bytes\n",sizeof (f));printf ("The amount of space allocated for double is %lu bytes\n",

sizeof (double));printf ("The amount of space allocated for variable d is %lu bytes\n",sizeof (d));printf ("The amount of space allocated for long double is %lu bytes\n",

sizeof (double));printf ("The amount of space allocated for variable d is %lu bytes\n",

sizeof (ld));printf ("The amount of space allocated constant PI is %lu bytes\n",sizeof (PI));return (0);

}

Output from FloatOut.c is as follows:

Example 1 : *23.140000*Example 2 : *237.148957*Example 3 : *2.371490e+02*Example 4 : *2.371490E+02*Example 5 : *237.149*Example 6 : * 237.1489568740*Example 7 : *237.1489568740 *Example 8 : *10.200000*--*3.440000*Example 9 : *10.200000*--*0.440000*Example 10: *2.67*--*1.49*Example 11: *162.67*--*208.49*Example 12: * 123.40*Example 13: *1234.119995*--*1.234120E+03*Example 14: *1234.120000*--*1.234120E+03*

Page 11: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[11]

Example 15: *1234.120000*--*1.234120E+03*Example 16: *123456.125000*--*1.234561E+05*Example 17: *123456.123450*--*1.234561E+05*Example 18: *123456.123450*--*1.234561E+05*Example 19: *123456792.000000000000000*--* 1.234567920000000E+08*Example 20: *123456789.123456789000000*--* 1.234567891234568E+08*Example 21: *123456789.123456789000000*--* 1.234567891234568E+08*Example 22: * 12345679020032.0000000*--*1.234568e+13*--*1.234568E+13*Example 23: * 12345678912345.1234500*--* 1.23457e+13*--* 1.23457E+13*Example 24: * 12345678912345.1234500*--* 1.23457e+13*--* 1.23457E+13*Example 25: * 2.3000e+02*Example 26: 1.234568e+13 1.234568e+13 1.234568e+13

The amount of space allocated for float is 4 bytesThe amount of space allocated for variable a is 4 bytesThe amount of space allocated for double is 12 bytesThe amount of space allocated for variable d is 12 bytesThe amount of space allocated for long double is 12 bytesThe amount of space allocated for variable d is 12 bytesThe amount of space allocated constant PI is 12 bytes

The constant PI is allocated as a long double. Note that this compiler/computer combination provides float data types with about eight significant digits of accuracy with numbers up to thirty–seven digits in length. Double/long double are provided with about eighteen digits of accuracy with numbers at least four thousand digits in length. This combination allows the computer scientist to work with very large and/or very small numbers.

Formatting Output for Memory Addresses

As previously mentioned, each memory location has a name, an address, and a value. The following code fragment declares two integer variables (I1 & I2) and initializes them (1,2 respectively); it also declares one float variable (F1) and initializes it (1.2).

int I1 = 1, I2 = 2;

floatF1 = 1.2;

The printf statement uses either %p or %lu or %u as the format specifier to display the actual memory addresses. Using this information, let us use the printf function to display the name, address, and value associated with each of the three variables above.

printf ("Variable %s : Address & %lu : Value %3d \n", "I1",&I1, I1);printf ("Variable %s : Address & %lu : Value %3d \n", "I2",&I2, I2);printf ("Variable %s : Address & %lu : Value %3.2f \n","F1",&F1, F1);

Output:

Variable I1 : Address & 4656302 : Value 1Variable I2 : Address & 4656300 : Value 2Variable F1 : Address & 4656296 : Value 1.20

The notation &I1 is read "the address of I1". C computer scientists will find displaying addresses quite useful in debugging programs. The format specifier

Page 12: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[12]

%p is used to display hexadecimal addresses and the format specifier %lu is used to display decimal addresses. We will use decimal display throughout this text.

No Boolean Data Type

Since the C language does not support any boolean data type, software engineers often define their own boolean data type as illustrated in chapter 5.

Exercises 2.11. Which of the following are valid integers? Explain why the others are

invalid.

a. 521b. –32.0c. 5,621d. +00784e. +65f. 6521492183g. –0

2. Which of the following are valid floats? Explain why the others are invalid.

a. 26.3b. +181.0c.-.14d. 492.e. +017.400f. 43E2g. –0.2E–3h. 43,162.3E5i. –176.52E+1j. 2.43000E+2

3. Change the following fixed–point decimals to floating–point decimals with exactly one nonzero digit to the left of the decimal.

a. 173.0b. 743927000000.0c. –0.000000023d. +014.768e.-5.2

4. Change the following floating–point decimals to fixed–point decimals.

a. –1.0046E+3b. 4.2E–8c. 9.020E10d. –4.615230E3e. 8.02E–3

5. Indicate the data type for each of the following:

a. –720b. –720.0c. 150E3d. 150

Page 13: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[13]

e. "150"f. "23.4E2"g. 23.4E–2

6. Write and run test a program to display the outside of an envelope similar to the following: (1) Substitute factual information for yourself and a friend, (2) Start Your information in column 1, and (3) Start the information of your friend in column 40.

Your NameYour StreetYour City, State Zip

Name of a FriendStreet of a FriendCity, State Zip of a Friend

7. Write and run test programs for each of the following:

a) Print the message Hello! using puts with no quotes inside the parenthesesHint:

puts (MESSAGE);b) Print the message Hello! across line one of the monitor using only the

putchar function. c) Print the message Hello! down column one of the monitor using only

the putchar function. d) Print the Letters A–F across line one of the monitor using only the

putchar function and numbers – no characters allowed. 8. For each of the following, write a program that would produce the

indicated output.

Score Price 86 $ 19.94 82 $100.00 79 $ 58.95

where ''S'' is in column 10.where ''P'' is in column 40.

9. Assume the hourly wages of five student employees are

3.65 4.10 2.89 5.00 4.50

Write a program that produces this output.

---------------------------------Employee Hourly Wage--------------------------------- 1 $ 3.65 2 $ 4.10

Page 14: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[14]

3 $ 2.89 4 $ 5.00 5 $ 4.50---------------------------------

10. What is the output from the following segment of code on your printer or terminal?

a) printf ("Average 1 = [%f]\n", 87.567);printf ("Average 2 = [%3.2f]\n", 87.567);printf ("Average 3 = [%3.2f]\n", 87.567);printf ("Average 4 = [%8.2f]\n", 87.567);printf ("Average 5 = [%-8.2f]\n", 87.567);printf ("Average 6 = [%5.3f]\n", 87.567);printf ("Average 7 = [%6.3f]\n", 87.567);

b) printf ("Exam 1 = [%i]\n", 87);printf ("Exam 2 = [%d]\n", 87);printf ("Exam 3 = [%1i]\n", 87);printf ("Exam 4 = [%4i]\n", 87);printf ("Exam 5 = [%-4i]\n", 87);

c) printf ("Name 1 = [%s]\n", "Jane Doe");printf ("Name 2 = [%12s]\n", "Jane Doe");printf ("Name 3 = [%-12s]\n", "Jane Doe");puts ("\"It Is Better To");puts ("Have Loved And Lost");printf ("Than To Have Never Loved At ");putchar ('A');putchar ('L');putchar ('L');putchar (34);putchar('\n');

d) putchar (84);putchar (72);putchar (69);putchar (32);putchar (69);putchar (78);putchar (68);putchar('\n');

11. What data type would be most appropriate for each of the following: (int, short int, long int, unsigned int, unsigned long int, unsigned short

int)

a. a single exam scoreb. world populationc. number of planets in the universed. elevation (in feet) with respect to sea level

12. What data type would be most appropriate for each of the following: (float, double, long double)

a. hourly pay rate

Page 15: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[15]

b. gross national productc. minimum waged. size of micro–organisms f. length and width (in feet) of a normal rooms

13. A C program has the following declarations:

main (){int a = 1, b = 2, c = 3;float d = 1.1, e = 2.2, f = 3.3;int g = 4;float h = 4.4;

Write the printf function calls which will display the following table for all eight of the variables in the order a,b,c,...,h.

Variable Name Address in Memory Contents a ? 1 b ? 2

... 2.2NumerationSystems

Decimal Numeration System (base 10)

Digits (base 10) = {0,1,2,3,4,5,6,7,8,9}.

Counting (10) = { 0 1 2 3 4 5 6 7 8 910 11 12 13 14 15 16 17 18 1920 21 22 23 24 25 26 27 28 2930 31 32 33 34 35 36 37 38 3940 41 42 43 44 45 46 47 48 4950 51 52 53 54 55 56 57 58 5960 61 62 63 64 65 66 67 68 6970 71 72 73 74 75 76 77 78 79

...

If W,X,Y,Z are decimal digits then the number of four consecutive digits (W ≠ 0) WXYZ = 10 * 10 * 10 * W + 10 * 10 * X + 10 * Y + Z

10*W + 10*X + 10*Y + 10*Z

Example 2.13175 (base 10) = WXYZ = 10 * 10 * 10 * 3 + 10 * 10 * 1 + 10 * 7 + 5

10*3 + 10*1 + 10*7 + 10*5

Remember that any non-zero number raised to the zero power is 1. Binary Numeration System (base 2)

Digits (base 2) = {0,1}.

Page 16: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[16]

Counting (2) = { 0 1 10 11 100 101 110 111

1000 10011010 10111100 11011110 1111 ...

Most of us are quite comfortable counting, adding, and subtracting decimal numbers, but the hardware circuitry of a computer is constructed in such a way that only the symbols 0's and 1's are applicable. The base–two numeration system that operates exclusively with 0's and 1's is called the binary numeration system. The binary system is the foundation upon which computer architecture is laid.

Convert Base 2 to Base 10 – Binary to Decimal -> if W,X,Y,Z are binary digits (W ≠ 0) then

WXYZ (base 2) = 2 * 2 * 2 * W + 2 * 2 * X + 2 * Y + Z

2*W + 2*X + 2*Y + 2*Z

Example 2.210010011 base (2) = (base 10)

2*1 +2*0 + 2*0 + 2*1 + 2*0 + 2*0 + 2*1 + 2*1 128 + 16 + 2 + 1 = 147

Convert Base 10 to Base 2 – Decimal to BinaryExample 2.3

175 (base 10) = (base 2)

[Euler's process for converting base 10 to base x ]

Step 1 : Set Problem to Divide the quotient side by the base (175/2)Step 2: 175/2 = New Quotient of 87 and New Remainder of 1

{Repeat Step 2 Until New Quotient = 0Step 2: 87/2 = New Quotient of 43 and New Remainder of 1Step 2: 43/2 = New Quotient of 21 and New Remainder of 1Step 2: 21/2 = New Quotient of 10 and New Remainder of 1Step 2: 10/2 = New Quotient of 5 and New Remainder of 0Step 2: 5/2 = New Quotient of 2 and New Remainder of 1Step 2: 2/2 = New Quotient of 1 and New Remainder of 0Step 2: 1/2 = New Quotient of 0 and New Remainder of 1

Step 3: Remainder Side contains the solution in Reverse Order

(bottom–up) = 10101111 (base 2)

Quotient | RemainderBase 2 175 |

-------------------------------------------------------

Page 17: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[17]

87 | 143 | 121 | 110 | 15 | 02 | 11 | 00 | 1

Many components of computer memory and storage capacity are binary rated:

1 KB (kilobyte) = 2bytes = 1,024 bytes.1 MB (kilobyte) = 2bytes = 1,048,576 bytes.1 GB (kilobyte) = 2bytes = 1,073,741,824 bytes.

Octal Numeration System (base 8)

Digits (base 8) = {0,1,2,3,4,5,6,7}.

Counting (8) = { 0 1 2 3 4 5 6 7 10 11 12 13 14 15 16 17 20 21 22 23 24 25 26 27 30 31 32 33 34 35 36 37 40 41 42 43 44 45 46 47 50 51 52 53 54 55 56 57 60 61 62 63 64 65 66 67 70 71 72 73 74 75 76 77

100 101 102 103 104 105 106 107110 111 112 113 114 115 116 117

The capacities of integrated circuit chips, floppy disks, hard disks, sectors, blocks, etc., will generally be binary related (often powers of two). Since representing large numbers in the binary system can be quite cumbersome, the octal and hexadecimal numeration systems must be introduced.

Convert Base 8 to Base 10 – Octal to Decimal -> if W,X,Y,Z are octal digits (W ≠ 0) then

WXYZ (base 8) = 8 * 8 * 8 * W + 8 * 8 * X + 8 * Y + Z

8*W + 8*X + 8*Y + 8*Z

Example 2.44031 base (8) = (base 10)

8*4 + 8*0 + 8*3 + 8*1 2048 + 24 + 1 = 2,073

Convert Base 10 to Base 8 – Decimal to OctalExample 2.5

175 (base 10) = (base 8)

[Euler's process for converting base 10 to base x ]

Page 18: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[18]

Step 1 : Set Problem to Divide the quotient side by the base (175/8)Step 2: 175/8 = New Quotient of 21 and New Remainder of 7

{Repeat Step 2 Until New Quotient = 0Step 2: 21/8 = New Quotient of 2 and New Remainder of 5Step 2: 2/8 = New Quotient of 0 and New Remainder of 2

Step 3: Remainder Side contains the solution in Reverse Order

(bottom–up) = 257 (base 8)

Quotient | RemainderBase 8 175 |

-------------------------------------------------------21 |

72 |

50 |

2

Convert Base 8 to Base 2 – Octal to BinaryExample 2.6

257 (base 8) = (base 2)

Base 8 Digits Base 2 Triplets--------------------- ------------------------- 0 0 0 0 1 0 0 1 2 0 1 0 3 0 1 1 4 1 0 0 5 1 0 1 6 1 1 0 7 1 1 1 ------------------------- 222

Change each Base 8 Digit to its Base 2 Triplet and delete leading 0s:257 (base 8) = 010 101 111 = 10101111 (base 2)

1427 (base 8) = 001 100 010 111 = 1100010111 (base 2)

Convert Base 2 to Base 8 – Binary to OctalExample 2.7

10101111 (base 2) = (base 8) Partition the base 2 digits into sets of 3 (right to left) and change each Base 2 Triplet to its respective Base 8 Digit:10101111 (base 2) = 010 101 111 (base 2) = 2 5 7 = 257 (base 8)

1100010111 (base 2) = 001 100 010 111 (base 2) = 1427 (base 8)

Hexadecimal Numeration System (base 16)

Digits (base 16) = {0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F} or {0,1,2,3,4,5,6,7,8,9,a.b.c.d.e.f}

Page 19: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[19]

Counting (16) = { 0 1 2 3 4 5 6 7 8 9 A B C D E F

10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F...

Convert Base 16 to Base 10 – Hexadecimal to Decimal -> if W,X,Y,Z are hexadecimal digits (W ≠ 0) then

WXYZ (base 16) = 16 * 16 * 16 * W + 16 * 16 * X + 16 * Y + Z

16*W + 16*X + 16*Y + 16*Z

Example 2.810b base (16) = (base 10)

16*1 + 16*0 + 16*b 256 + 11 = 267

Example 2.996 base (16) = (base 10)

16*9 + 16*6 144 + 6 = 150

Convert Base 10 to Base 16 – Decimal to HexadecimalExample 2.10

175 (base 10) = (base 16)

[Euler's process for converting base 10 to base x ]

Step 1 : Set Problem to Divide the quotient side by the base (175/16)Step 2: 175/16 = New Quotient of a and New Remainder of f

{Repeat Step 2 Until New Quotient = 0Step 2: a/16 = New Quotient of 0 and New Remainder of a

Step 3: Remainder Side contains the solution in Reverse Order

(bottom–up) = af (base 16)

Quotient | RemainderBase 16 175 |

-------------------------------------------------------a | f0 | a

150 (base 10) = (base 16)

Quotient | RemainderBase 16 150 |

-------------------------------------------------------9 | 60 | 9

Page 20: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[20]

Convert Base 16 to Base 2 – Hexadecimal to BinaryExample 2.11

af (base 16) = (base 2)

Base 16 Digits Base 2 Quads----------------------- ---------------------- 0 0000 1 0001 2 0010 3 0011 4 0100 5 0101 6 0110 7 0111 8 1000 9 1001 a 1010 b 1011 c 1100 d 1101 e 1110 f 1111

Change each Base 16 Digit to its Base 2 Quad and delete leading 0s:af (base 16) = 1010 1111 = 10101111 (base 2)

317 (base 16) = 0011 0001 0111 = 1100010111 (base 2)

Convert Base 2 to Base 16 – Binary to HexadecimalExample 2.12

10101111 (base 2) = (base 16) Partition the base 2 digits into sets of 4 (right to left) and change each Base 2 Quad to its respective Base 16 Digit:

1010 1111 (base 2) = a f = af (base 16)

1100010111 (base 2) = 0011 0001 0111 (base 2) = 317 (base 16)

Since the conversion between octal/hexadecimal and binary is so easily done, main memory dumps are often generated in octal or hexadecimal.

Defining Constants with Octal and Hexadecimal Bases

# define W 011 W = Octal 11 (9 Base 10)# define X 023 X = Octal 23 (19 Base 10)

# define Y 0X11 Y = Hexadecimal 11 (17 Base 10)# define Z 0XA Z = Hexadecimal A (10 Base 10)

The four integer constants defined above will contain integer values 9, 19, 17, and 10. The leading 0 indicates that the integer constant is defined in octal form. The leading 0X indicates that the integer constant is in hexadecimal form.

Exercises 2.21. List the rules for forming valid identifiers.

Page 21: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[21]

2. Which of the following are valid identifiers? Give an explanation for those that are invalid.

a. 7Upb. Payrollc. room222d. Name Liste. af. A1g. 1Ah. Time&Placek. ListOfEmployeesl. Lima,Ohiom. _Daten. No_employeeso. NO_EMPLOYEESp. a*b

3. Name the three main sections of a C program.

4. Write constant definition statements for the following:

a. Your nameb. Your agec. Your birth dated. Your birthplace

5. Which of the following are valid constant declarations? Give an explanation for those that are invalid.

a. # define PAY_RATE 6.25b. # define PAY_RATE = 6.25c. # define COMPANY 'General Motors'd. # define COMPANY 'General Motors';e. # define COMPANY "General Motors'f. # define COMPANY "General Motors";g. # define COMPANY "General Motors" h. # define Name "Peter Pan";i. # define LETTER_A 'A'j. # define LETTER_B "B"k. # define LETTER_C 'C';

6. Complete the following:

a. 512 (base 10) = (base 2)b. 512 (base 10) = (base 8)c. 51 (base 10) = (base 16)d. 1000 (base 10) = (base 2)e. 1000 (base 10) = (base 8)f. 100 (base 10) = (base 16)g. 10100 (base 2) = (base 10)h. 10100 (base 2) = (base 8)i. 10100 (base 2) = (base 16)j. 11100010 (base 2) = (base 10)k. 11100010 (base 2) = (base 8)l. 11100010 (base 2) = (base 16)m. 24 (base 8) = (base 10)

Page 22: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[22]

n. 24 (base 8) = (base 2)o. 735 (base 8) = (base 10)p. 736 (base 8) = (base 2)q. 12 (base 16) = (base 10)r. 12 (base 16) = (base 2)s. 2D (base 16) = (base 10)t. 2d (base 16) = (base 2)u. 2D (base 16) = (base 8)v. 1AC (base 16) = (base 10)w. 1AC (base 16) = (base 2)x. 1ac (base 16) = (base 8)

7. Write a program which fills base 10 constant (A) with 11, fills base 8 constant (B) with octal 11, and fills base 16 constant with hexadecimal 11. Execute the following main program and record the output.

main (){printf ("A = %d\n",A);printf ("B = %d\n",B);printf ("C = %d\n",C);

} 2.3RepresentingIntegers in Memory

Unsigned Binary Addition

Unsigned binary addition is very similar to that of unsigned decimal addition. The four basic facts are as follow:

0 + 0 = 01 + 0 = 10 + 1 + 11 + 1 = 10

Note the carry or regrouping that must occur when the sum is greater than one.Example 2.13: 1 1 1 1 1

1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1+ 1 0 0 1 = + 1 0 0 1 = + 1 0 0 1 = + 1 0 0 1 = + 1 0 0 1 0 1 0 1 1 0 1 0 1 1 0

Example 2.14: 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1+ 1 1 = + 0 0 1 1 = + 0 0 1 1 = + 0 0 1 1 = + 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0

Example 2.15: 1 1 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1+ 1 1 0 0 = + 1 1 0 0 = + 1 1 0 0 = + 1 1 0 0 = + 1 1 0 0 1 0 1 0 0 1 1 1 0 0 1

Integer Overflow and Integer Underflow

Arithmetic operations with computers have some limitations. One of these is the problem of overflow. Integer overflow occurs when an integer expression exceeds the value of INT_MAX. Float overflow occurs when the absolute value of

Page 23: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[23]

a float is too large to fit into a float memory location. Ideally, an error message should be given when overflow occurs; unfortunately, that is not generally the case with C compilers. Most systems just assign an erroneous value and keep on computing. You should be sure to check limitations for your system.

A second problem occurs when working with floats. If a float number is too small to be represented, it is replaced by zero. This is called underflow. Thus, your computations may produce a float of the magnitude 1.0* 10, but your system could replace this with a zero.

In general, underflow is less of a problem than overflow. You should, however, always guard against both possibilities when performing numerical computations.

Storage of Positive Integers

A Memory Manager portion of the C compiler has the responsibility of allocating that portion of memory available to the compiler. As indicated in chapter 1, the compiler may be one of several applications in memory at this moment in time. The Detailed Memory Map is a very detailed bit level picture of memory. Only by examining things at the bit level will we be able to understand the three different possible techniques for storage of negative integers. The starting address portion of the detailed memory map indicates where a particular variable is stored in memory at this time; these addresses will change as the program and data change. For the examples below, let us assume that the memory manager begins to allocate memory with address 2233552; note that the memory manager, in the following examples, is allocated contiguously in the negative direction.

Example 2.16: Show the detailed storage memory map for the following:int

Total = 300;

When the code (above) is executed, the following things happen:

(1) The memory manager allocates 2 bytes (which is sizeof (int)) of memory and associates it with the symbolic name Total. The actual starting address of this two–byte field does not generally concern the C programmer.

(2) This two–byte field consists of 16 bits. The Low–Byte contains bits 0–7. The High–Byte contains bits 8–15. Note that the bit numbering starts with 0. The high–bit (#15 in this case) is called the sign–bit. The sign–bit is assigned a 0 for positive numbers. The sign–bit is assigned a 1 for negative numbers. Since the number (300) assigned to the integer field (Total) is positive, the sign–bit is 0.

(3) The number to be assigned (300) is converted to binary (100101100) and placed in the 16 bit field. If the programmer makes a mistake and assigns a number with more than 15 binary digits (integer overflow), the variable will contain erroneous data. It is the computer scientist's responsibility to make sure that the variable container is sufficiently large to hold the assigned value.

(4) Place 0's in any of the remaining bits.

Example 2.17: Show the detailed storage memory map for the following:int

Amount = 6444;

Sign–Magnitude Storage of Negative Integers

Page 24: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[24]

Sign–magnitude storage is one of three standard storage techniques for negative integers. Examine the sign-magnitude explanations and illustrations in the four examples which follow.

Example 2.18: Show the detailed sign–magnitude storage memory map for the following:int

Total2 = –300;

When the code (above) is executed, the following things happen:

(1) The memory manager allocates 2 bytes (which is sizeof (int)) of memory and associates it with the symbolic name Total2.

(2) This two–byte field consists of 16 bits. The Low–Byte contains bits 0–7. The High–Byte contains bits 8–15. Note that the bit numbering starts with 0. The high–bit (#15 in this case) is called the sign–bit. The sign–bit is assigned a 0 for positive numbers. The sign–bit is assigned a 1 for negative numbers. Since the number (-300) assigned to the integer field (Total) is negative, the sign–bit is 1.

(3) The number to be assigned (300) is converted to binary (100101100) and placed in the 16 bit field. If the programmer makes a mistake and assigns a number with more than 15 binary digits (integer overflow), the variable will contain erroneous data. It is the computer scientist's responsibility to make sure that the variable container is sufficiently large to hold the assigned value.

(4) Place 0's in any of the remaining bits.

Example 2.19: Show the detailed sign–magnitude storage memory map for the following:int Length = –256;

Example 2.20: Show the detailed sign–magnitude storage memory map for the following:int Max = 32767; /* Largest Positive Integer in Sign–Magnitude*/

Example 2.21: Show the detailed sign–magnitude storage memory map for the following:int Min = -32767; /* Largest Negative Integer in Sign–Magnitude*/

Sign–magnitude storage is not used on computers today. One of the problems with implementing sign–magnitude storage techniques from a hardware reference is the addition operation. Let us add +6 and –6.

One's Complement Storage of Negative Integers

Page 25: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[25]

One's complement storage is second of three standard storage techniques for negative integers. Examine the one's complement explanations and illustrations in the three examples which follow.

Example 2.22: Show the detailed one's complement storage memory map for the following:int

BowlingScore = –300;

To find the one's complement storage for negative numbers do the following:

(1) Represent the number in the positive form.

(2) Complement each and every digit – Change all 0s to 1s and change all 1s to 0s.

Example 2.23: Show the detailed one's complement storage memory map for the following:int Max2 = 32767; /* Largest Positive Integer in One's Complement*/

Example 2.24: Show the detailed one's complement storage memory map for the following:int Min2 = -32767; /*Smallest Negative Integer in One's Complement*/

Hardware can easily be constructed for the addition of integers. In order to add two numbers, the hardware performs the four basic addition facts on the two integers (one digit at a time from right to left); the carry bit holds the regrouping from the high bit. The carry bit is added to the partial sum to calculate the sum.

Subtraction can be performed with the same hardware configuration as that used for addition by changing the subtraction problem to an equivalent addition problem. Since 10 – (+6) = 10 + (-6), subtraction is performed by negating the minuend (6 –6) and then adding the minuend (-6), the subtrahend (10), and the carry bit(1) to generate the answer. The one's complement is sometimes referred to as the negation or the NOT operation.

Two's Complement Storage of Integers

Two's complement storage is third of three standard storage techniques for negative integers. Examine the two's complement explanations and illustrations in the four examples which follow.

Example 2.25: Show the detailed two's complement storage memory map for the following:int

Page 26: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[26]

NoScore = –300;

To find the two's complement for negative numbers do the following:

(1) Represent the Number in the Positive Form.

(2) Complement each and every digit (One's Complement) – Change all 0's to 1's and change all 1's to 0's.

(3) Add 1.

Example 2.26:

Show the detailed two's complement storage memory map for the following:int Max3 = 32767; /* Largest Positive Integer in Two's Complement*/

Example 2.27: Show the detailed two's complement storage memory map for the following:int No = –255;

Example 2.28: Show the detailed two's complement storage memory map for the following:int Min3 = -32768; /* Largest Negative Integer in Two's Complement*/

Two's complement is the most commonly used storage technique for negative integers. Hardware can easily be constructed for the addition operation. The Carry Bit is discarded!

Subtraction can be performed with the same hardware configuration as that used for addition by changing the subtraction problem to an equivalent addition problem. Since 10 – (+6) = 10 + (-6), subtraction is performed by negating the minuend (6 –6) and then adding the minuend (-6) to the subtrahend (10) to generate the answer. Since the range of integers for this textbook is –32,768 to 32,767, the compiler/computer combination used for this textbook uses two's complement storage technique for negative integers.

Page 27: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[27]

Storage of long int

Storage techniques for long int are an extension of the int techniques. The major difference is that there are 32 bits (4 bytes). The bits are numbered 0–31. The sign–bit (high–bit) is bit #31.

Example 2.29: Show the detailed memory map for the following: (all three same for positive )long int Quantity = 255L;

Example 2.30: Show the detailed all three storage memory maps for the following:long int Range = –255L;

A NOTE OF INTEREST

Sex Differences in the Association Between Secondary School Students' Attitudes

Toward Mathematics and Toward Computers

Sex differences in secondary school students' attitudes toward mathematics are well documented (Fennema, 1980), with female students consistently displaying less positive attitudes than male students (Fennema & Sherman, 1977). Because attitude is related to participation and achievement in mathematics (Armstrong & Price, 1982), many intervention strategies have as their aim the development of more positive attitudes toward mathematics among young women (Fox, 1980; Sells, 1980).

The same types of sex differences that are associated with secondary students and their attitudes toward mathematics are now being seen with regard to computer studies in secondary school (Lockheed, 1985; Lockheed & Frakt, 1984). Many educators believe that special attention should be given to the development of approaches to computer use in secondary school that might increase the interest level or motivation of young women (Sanders, 1985). Some researchers claim that the association of computer studies with mathematics is one of the factors underlying the relatively negative attitudes that adolescent women are displaying toward computers (Lockheed & Frakt, 1984; Ramierez, 1983). However, others believe that the use of computers within the context of mathematics instruction can enhance interest in mathematics––for both men and women (Glass, 1984; Kelman et al., 1983). Thus there seems to be a variety of opinions regarding effective procedures to enhance women's attitudes toward either mathematics or computers and regarding the appropriateness of incorporating computer experiences into mathematics instruction. The purpose of this study was to explore the general question of sex differences in the association between secondary school students' attitudes toward computers and toward mathematics by considering the following questions:

1. Is there a relationship between secondary school students' attitudes toward mathematics and their attitudes towardcomputers? Is there a sex difference in the relationship?

2. Is there a relationship between use of computers within a mathematics course and attitudes toward computers? Is there a sex difference in the relationship?

Page 28: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[28]

A significant association between secondary school students' attitudes toward mathematics and their attitudes toward computers was shown in the study. Sex differences in the nature of this association suggested that female secondary school students are more likely than male students to associate negative attitudes toward mathematics with generally negative opinions about computer use and with stereotypes about computer users. The common practices of inserting computer components into junior secondary school mathematics classes, staffing computer studies and computer science courses with mathematics teachers, and developing such courses around mathematics–related examples and topics (Lockheed & Frakt, 1984) may produce a negative predisposition toward the computer activities for female students. Because attitude, participation, and achievement are frequently interrelated for secondary school students (Armstrong, 1979; Armstrong & Price, 1982), the repercussions of the transfer of attitudes toward mathematics to the new construct of attitudes toward computers would seem to be deleterious for many female students. There are many important applications of computers, such as word processing and information retrieval, that are nonmathematical in nature. It has been suggested that secondary school computer experiences should be delivered around such topics to reduce the impact of a negative mathematics–computer association for female students (Lockheed & Frakt, 1984; Sanders, 1985). The results of the present study support the value of this suggestion.

Numeric ConversionsExample 2.31

The code fragment below fills an integer container with a float constant, a float variable, and then a float expression. Filling an integer container with a floating point number automatically converts (casts) the float into integer form; this conversion truncates (chops off/discards) the fractional portion to the right of the decimal point.

float SumFloat = 3.77;

int Sum;

Sum = 2.35; /* float constant */printf ("Sum = %d",Sum); -------------------------> Sum = 2Sum = SumFloat; /* float variable */printf ("Sum = %d",Sum); -------------------------> Sum = 3Sum = 3.999 + 1; /* float expression */printf ("Sum = %d",Sum); -------------------------> Sum = 4

Example 2.32The code fragment below fills an integer container with a long integer

constant, a long integer variable, and then a long integer expression. Filling an integer container with a long integer automatically converts (casts) the long integer into integer form; this conversion will work correctly if and only if the long integer is in the range: INT_MIN <= long int <= INT_MAX.

long int SumLong = 36;

int Sum;

Sum = 35L; /* long constant */printf ("Sum = %d",Sum); -------------------------> Sum = 35Sum = SumLong; /* long variable */printf ("Sum = %d",Sum); -------------------------> Sum = 36Sum = 20L + 17; /* long expression */printf ("Sum = %d",Sum); -------------------------> Sum = 37

Page 29: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[29]

Notice what happens when the long integer is outside the valid integer range (below).

long int SumLong = 32768;

int Sum;

Sum = 32768; /* long constant */printf ("Sum = %d",Sum); -------------------------> Sum = –32768Sum = SumLong; /* long variable */printf ("Sum = %d",Sum); -------------------------> Sum = –32768

It is not essential for you to understand why (int) 32768 = –32768. The explanation is left as a problem for students who understand two's complement storage of negative numbers. It is important for all to realize that there is a potential for error generated when the computer scientist incorrectly selects a variable data type and overflows that variable.

Example 2.33The code fragment below fills an integer container with a character constant

and a character variable. Filling an integer container with a constant automatically places the corresponding ASCII value into the integer container.

char NewChar = 'B';

int Sum;

Sum = 'A'; /* char constant */printf ("Sum = %d",Sum); -------------------------> Sum = 65Sum = NewChar; /* float variable */printf ("Sum = %d",Sum); -------------------------> Sum = 66

Mixed Expressions

Arithmetic expressions using data of two or more types are called mixed–mode expressions. In a mixed–mode expression involving both int and float data types, the value will be of type float.

The result of 15 + 3.2 is 18.2 (as opposed to truncating the integer to get 18).

Exercises 2.31. Add each of the following unsigned binary numbers

a. 100 + 101b. 11011 + 10101c. 11001 + 111

2. Show the Detailed Memory Map of the following integers if Sign–Magnitude Storage were used to store negative numbers. Assume that your compiler allocates memory address 564882 for all maps.a. +15b. –15c. +250d. –250e. +0

Page 30: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[30]

f. –0

3. Show the Detailed Memory Map of the following integers if One's Complement Storage were used to store negative numbers. Assume that your compiler allocates memory address 564882 for all maps.a. +15b. –15c. +250d. –250e. +0f. –0

4. Show the Detailed Memory Map of the following integers if Two's Complement Storage were used to store negative numbers. Assume that your compiler allocates memory address 564882 for all maps.a. +15b. –15c. +250d. –250e. +0f. –0

5. Draw a picture representing each of the following integer additon problems using One's Complement Storage additon. (End Around Carry)a. 8 + (-3)b. 8 + 3

6. Draw a picture representing each of the following integer additon problems using Two's Complement Storage additon. (Discard the Carry)a. 8 + (-3)b. 8 + 3

7. What is the output produced by the following program?main(){printf ("Expression Value\n");printf ("---------- -----\n");printf ("10/5 %12.3f\n" , 10 / 5);printf ("2.0+7*(-1)%12.3f\n", 2.0 + 7 * (-1));printf ("7/3 %12d\n",7/3); /* int div truncates remainder */printf ("8/3 %12d\n",8/3); /* int div truncates remainder */printf ("8/3 %12.3f\n",8/3);/* int div produces int*/printf ("8.0/3.0 %12.3f\n",8.0/3.0);/*float div produces float*/printf ("8.0/3 %12.3f\n",8.0/3); /* mixed div produces float*/return (0);

}

8. The output from the following program generates hexadecimal code which relates to the detailed memory maps. What is the output produced from the following program?main(){int

x = 0;printf ("%8d %4X\n", x,x);

x = 1;

Page 31: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[31]

printf ("%8d %4X\n", x,x);

x = –1;printf ("%8d %4X\n", x,x);

x = 2;printf ("%8d %4X\n", x,x);

x = –2;printf ("%8d %4X\n", x,x);

x = 255;printf ("%8d %4X\n", x,x);

x = 32767;printf ("%8d %4X (INT_MAX) \n", x,x);

x = –32767;printf ("%8d %4X\n", x,x);

x = –32768;printf ("%8d %4X (INT_MIN) \n", x,x);

/* 32768 = 10000000 00000000 (binary) = 8000 (hex) = –32768 */x = 32768;printf ("%8d %4X (Overflow Container) \n", x,x);

/* 32769 = 10000000 00000001 (binary) = 8001 (hex) = –32767 */x = +32769;printf ("%8d %4X (Overflow Container) \n", x,x);

x = +32770;printf ("%8d %4X (Overflow Container) \n", x,x);

x = +32771;printf ("%8d %4X (Overflow Container) \n", x,x);

x = +32772;printf ("%8d %4X (Overflow Container) \n", x,x);return (0);

}

SUMMARYKey Terms / Words

ASCIIassignment statementbinary (base 2) numberbitbytebyte addressablecharacter setconstantdata typedebuggingdetailed memoryh mapdecimal (base 10) number

floatfloating pointformattinghexadecimal (base 16) numberhigh byteintlonglow bytememory sketchoctal (base 8) numberobject programone's complement

putsscanfshortsign bitsign-magnitudestring constantstring variablestdouttest programtwo's complementunderflowvariable

Page 32: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[32]

doubleEBCDICescape sequence

overflowprintfputchar

wordword addressable

Key Concepts

The range of digits is always from 0 to (Base -1).

Any non-zero number raised to the zero power is 1.

It is the computer scientist's responsibility, in all languages, to select appropriate variable data types.

The ANSI C standards specify minimal standards to which each data type must comply. In order to more fully utilize the power and capacity of each computer, the ANSI C standards may be exceeded.

Most microcomputer compilers exceed the minimal limits on the short integer and unsigned short integer; they are often two bytes.

Since software is often run a variety of different computers, it is best to develop your software in accordance with the minimal ANSI standards.

Each memory location has a name, an address, and a value.

The number of format specifiers in a printf control string should match the number of arguments after the control string.

In the char data type, each character is associated with an integer

The discipline of computer science combines methodologies from the natural sciences, mathematics, logic, and engineering.

Extra spaces and blank lines are ignored in C.

Output is generated by using putchar, printf, and/or puts statements.

––––––––––––––––––––PROGRAMMING PROBLEMS––––––––––––––––––––

1. Use the editor to create a text file, called IntLimit.c, that contains the code listed program IntLimit.c of section 2.1. Compile and execute the program.Complete the table:

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––Variable Data Type ANSI Minimum Your Compiler Value #

Bytes––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––SHRT_MIN intSHRT_MAXINT_MININT_MAXLONG_MINLONG_MAX

USHRT_MINUSHRT_MAX

Page 33: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[33]

UINT_MINUINT_MAXULONG_MINULONG_MAX––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

2. Use the editor to create a text file, called FltLimit.c, that contains the code listed program FltLimit.c of section 2.1. Compile and execute the program.Complete the table:

–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

Data Type ANSI Precision Your Compiler Precision # Bytes

–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

floatdoublelong double

–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

3. Use your editor to create a text file, called MyInits.c, that displays your initials in block capital letters.

JJJJJ A CC J A A C C J A A C J AAAAA C J J A A C C JJ A A CC

4. Write a program that produces the following output. Start Student in column 20 and Test in Column 40.

Student Name Test Score

Adams, Mike 73Conley, Theresa 86Samson, Ron 92O'Malley, Colleen 81

5. The Great Lakes Shipping Company is going to use a computer program to generate billing statements for their customers. The heading of each bill is to be

GREAT LAKES SHIPPING COMPANY SAULT STE. MARIE, MICHIGAN------------------------------------------------------------------------------------------------ Thank you for doing business with our company. The information listed below was used to determine your total cargo fee. We hope you were satisfied with our service.------------------------------------------------------------------------------------------------

Page 34: thicks/1320/Handouts/AAbout... · Web viewWord[10]; The last character in every string is an end-of-string marker (ASCII 0). The following will declare (allocate memory for) a string

[34]

CARGO TONNAGE RATE/TON TOTAL DUE

Write a complete C program that produces this heading.

6. Write a complete program that produces the following table:

Rectangle Width Rectangle Length Rectangle Area-------------------------- ---------------------------- ----------------------- 4 2 8 21 5 105

7. Write a complete program that produces the following output:

Hourly Wage Hours Worked Gross Pay---------------------- ----------------------- ---------------- 5.0 20.0 100.00 7.50 15.25 114.375