Lecture03-formattedi - EE312 SOFTWARE DESIGN AND IMPLEMENTATION I LECTURE 3(CONTINUED FORMATTED I/O Spring 2012 Professor Suzanne Barber

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: EE312: SOFTWARE DESIGN AND IMPLEMENTATION I LECTURE 3 (CONTINUED): FORMATTED I/O Spring 2012 Professor Suzanne Barber [email protected] ACES 5.440 Office Hours: MW 11 am Noon, or by appointment Announcements From the the text book: For today (and the previous lectures): Chapters 2, 3, and 4 To prepare for the next lecture: Chapters 5 and 6 For this lecture: Finishing up Basic C constructs Numeric Expressions FormaHed input and output (I/O) 2 Compound Assignment In addiLon to the simple assignment operator =, C provides ten compound assignment operators, including += -= *= /= %= E.g., the expression v += e; is equivalent to v = v + e; except that v is evaluated only once in the former expression The compound assignment operators have the same properLes as the = operator They re right associaLve and can be used in arbitrary expressions. The use of these operators is discouraged in your programs i = 5; j = 2; i -= j; /* i is now 3 */ i = 5; j = 2; i *= j; /* i is now 10 */ i = 5; j = 2; i /= j; /* i is now 2 */ i = 5; j = 2; i %= j; /* i is now 1 */ 3 i = 5; j = 2; i += j; /* i is now 7 */ Defining Symbolic Constants Two ways - macro definiLon or using const in the variable declaraLon A macro definiLon has the form #define idenLfier replacement-list For example: n n n #define N 100 /* replaces the symbol N with 100 throughout the program */ . . . int i = N 1; If the replacement list contains operators, it is best to enclose it in parentheses. More on why later. Macro definiLons are handled by the C preprocessor (Ch. 14). n Examples: #define EOF (-1) const int EOF = -1; #define TWO_PI (2*3.14159) const float TWO_PI = 2*3.14159; 4 Symbolic Constants (cont.) Advantages of defining symbolic constants: Programs are easier to read. Programs are easier to modify. Helps reduce errors of inconsistent use, as well as typographical errors. Style issues by convenLon use all capital leHers for constant idenLfiers and separate parts of the name with an underscore "Magic numbers" should generally not appear in your programs. n If you need to use a number besides -1, 0, 1, or 2, declare a symbolic constant 5 EE312: SOFTWARE DESIGN AND IMPLEMENTATION I LECTURE 4: NUMERIC EXPRESSIONS Spring 2012 Professor Suzanne Barber [email protected] ACES 5.440 Office Hours: MW 11 am Noon, or by appointment ArithmeLc Operators The arithmeLc operators are: n n n n n n n + unary plus - unary minus * mulLplicaLon / division % modulo division remainder + addiLon - subtracLon The value of i % j is the remainder when i is divided by j For example, the value of 10 % 3 is 1; the value of 12 % 4 is 0 The % operator requires integer operands; all other operators allow either integer or floaLng-point operands If both operands are integers, / truncates the result toward 0 There is no exponenLaLon operator in C 7 Operator Precedence When an expression contains more than one operator, the meaning of the expression may not be clear: does i + j * k mean (i + j) * k or i + (j * k) ? In C, this potenLal ambiguity is resolved by the following operator precedence scheme. n n n Highest: + - (unary) * / % Lowest: + - (binary) Examples: i + j * k means i + (j * k) -i * -j means (-i) * (-j) +i + j / k means (+i) + (j / k) 8 AssociaLvity Operator precedence rules aren t enough when an expression contains two or more operators at the same level of precedence The binary arithmeLc operators are all lei associaLve (group from lei to right); unary operators are right associaLve Examples of associaLvity: n n n n i - j - k means (i - j) - k i * j / k means (i * j) / k i - j * i + k means (i - (j * i)) + k - - i means -(-i) All problems of ambiguity are overcome by using ( ) 9 Increment and Decrement Operators The ++ and -- operators increment and decrement variables. Both operators are unary. Either operator can be prefix or posjix: n n ++i i++ --i i-- When used as a prefix operator, ++ increments the variable before its value is fetched: i = 1; prinj("i is %d\n", ++i); /* prints "i is 2" */ When used as a posjix operator, ++ increments the variable aier its value is fetched: i = 1; prinj("i is %d\n", i++); /* prints "i is 1" */ The -- operator has similar properLes You can t ++ or - - an expression Don t embed these inside of other expressions (unclear semanLcs) Use these for counters and loop control 10 Expression Statements C allows expressions to be used as statements Quirky a + b c * d; The value of the expression is the value of the statement Which is then discarded no variable is changed Except for increment/decrement statements these are useless and not recommended 11 What s the value of y ? int x =1, y = 6, z = 7; z = z + 1; y = x * z + 14 y % 5 + z / 4 ; Wouldn't it be easier to calculate with parenthesis? y =((((x * z) + 14) (y % 5)) + (z/4)); 28 12 Compute the Volume /* this program computes and outputs the volume of a box */ #include <stdio.h> int main(void) { int height, length, width, volume; height = 5; length = 20; width = 10; volume = height * length * width; printf ("The height is %d\n", height); printf ("The length is %d\n", length); printf ("The width is %d\n", width); printf ("The volume is %d\n", volume); return 0; } 13 Converting Fahrenheit to Celsius /* convert a given fahrenheit temperature to celsius */ #include <stdio.h> #define FREEZING_PT 32.0 #define SCALE_FACTOR (5.0 / 9.0) int main(void) { float fahrenheit, celsius; printf ("Enter Fahrenheit temperature: "); scanf ("%f", &fahrenheit); celsius = SCALE_FACTOR * (fahrenheit - FREEZING_PT); printf ("\nCelsius equivalent is: %.1f\n", celsius); return 0; } 14 Converting Fahrenheit to Celsius /* convert a given fahrenheit temperature to celsius */ #include <stdio.h> int main(void) { const float FREEZING_PT = 32.0; const float SCALE_FACTOR = 5.0 / 9.0; float fahrenheit, celsius; printf ("Enter Fahrenheit temperature: "); scanf ("%f", &fahrenheit); celsius = SCALE_FACTOR * (fahrenheit - FREEZING_PT); printf ("\nCelsius equivalent is: %.1f\n", celsius); return 0; } 15 C s Numeric Type Categories integer (whole numbers) FloaLng-point (fracLonal decimal) You have limited control over how much memory is used how that memory is used The details are in Ch. 7 (more later) 16 Integers May be declared as signed (default) or unsigned Lei most bit used to indicate sign (in 2 s complement format) 32 bit machine int format is (4 bytes): 01111111 11111111 11111111 11111111 Range signed: -231 to 231-1 unsigned 0 to 232-1 You could use unsigned when number is non-negaLve and addiLonal magnitude is needed 17 Integers (cont) Control over memory usage int is the natural word size of a specific computer n what is most efficient for that cpu/memory short usually halves number of bits long usually increases number of bits For maximum portability use int or short int for integers that won t exceed 32,767 and long int for all other integers 18 Typical Integer Value Ranges 32-bit Machine Data Type 16 bits short int Smallest Value -32,768 Largest Value 32,767 65,535 2,147,483,647 4,294,967,295 2,147,483,647 4,294,967,295 unsigned short int 0 32 bits int unsigned int 32 bits long int unsigned long int 64-bit Machine long int unsigned long int 9,223,372,036,854,775,808 0 -2,147,483,648 0 -2,147,483,648 0 9,223,372,036,854,770,000 18,446,744,073,709,500,000 19 Integer Literals These are constant values that cannot be altered during program execuLon They may appear in one of three formats: decimal (base 10, digits 0-9) n 15, 255, 32767 octal (base 8, digits 0-7, must begin with 0) n 017, 0377, 077777 hexadecimal (base 16, digits 0-9,a-f, must begin with 0x) n 0xf, 0xff, 0xfff n hexadecimal digits may be in upper or lower case, 0xFf or 0xff or 0xFF Octal and hex are mostly used in low level programs 20 Integer Literals (cont) All forms (decimal, octal, hex) are all represented (internally) the same. 10 + 015 + 0x20 ??? Answer is 55 (in decimal) RepresentaLon Rules if value falls within int type int n otherwise it s a long int To force long or unsigned representaLon, follow constant with U and/or L For examples n 15U 0377L 0x7ffffffffUL 21 FloaLng Point Capable of represenLng fracLonal numbers Numbers are stored in 3 parts: Sign bit (+ / -) Exponent (10n, number of bits size) FracLon (number of bits precision) Three floaLng point formats are: float single precision double double precision long double extended precision Nearly all engineering calculaLons should use double or long double 22 FloaLng Point Literals 57.0 57. 57.0e0 5.7e+1 .57e2 570.e-1 Must contain decimal point and/or exponent By default stored as double-precision numbers F or f, L or l can be used to force storage format IEEE Standard 754 Floa8ng Point Characteris8cs Smallest Value (+) 1.17x10-38 2.22x10-308 Largest Value (+) 3.40x10-38 1.79x10-308 Precision Type float (32) double (64) Up to 6 digits Up to 15 digits 23 long double is not defined by this standard and is usually 80 or 128 bits Quick Quiz double x = 7.0; int j = 2; x = (x 3) + 1.5 * j 7 / j; 3 /* x is ??? */ 4.0 + 3.0 7.0 - 4.0 24 Converting Fahrenheit to Celsius /* convert a given fahrenheit temperature to celsius */ #include <stdio.h> int main(void) { const double FREEZING_PT = 32.0; const double SCALE_FACTOR = 5.0 / 9.0; double fahrenheit, celsius; printf ("Enter Fahrenheit temperature: "); scanf ("%lf", &fahrenheit); celsius = SCALE_FACTOR * (fahrenheit - FREEZING_PT); printf ("\nCelsius equivalent is: %.1f\n", celsius); return 0; } 25 C Math Library FuncLons See Ch. 23.3 and appendix D #include <math.h> Trig funcLons Hyperbolic funcLons ExponenLal funcLons Logarithmic funcLons Power funcLons Nearest integer Absolute value Remainder funcLons FuncLons are called by name (values-passed), e.g., double x; x = sqrt (3.0); /* x will be 1.73205 */ 26 EE312: SOFTWARE DESIGN AND IMPLEMENTATION I LECTURE 5: FORMATTED INPUT AND OUTPUT Spring 2012 Professor Suzanne Barber [email protected] ACES 5.440 Office Hours: MW 11 am Noon, or by appointment FormaHed Input and Output: simplifying process of inpuwng values into and out of your program while its running For stdio library contains funcLons for: reading values from the keyboard (the standard input device): scanf() device) prinj() wriLng out values to the screen (the standard output Rely on provided format specificaLon You may use these in your assignments Input device values Your program running on the computer values Output device 28 printf() function these are optional prinj ( format-string-in-quotes ,list-of-values); Defined in a library. Declared in <stdio.h> printf ("Double %d is %d \n", x, 2 * x ); Format string Conversion specifications Values to be printed Escape character for output control 29 Escape Sequences Format string someLmes contains control characters (such as tab and newline) or characters that have a special meaning in C (such as "). n n n Consist of \ followed by another character, e.g: alert (bell) \a backslash \\ backspace \b quesLon mark \? single quote \ double quote \ new-line \n horizontal tab \t verLcal tab \v The \t escape causes the cursor to move to the next tab stop useful for output of columns/tables of data The \" escape allows us to print the double quote character: prinj("\"Hello!\""); The format string may contain any number of escape sequences: n prinj("Item\tUnit\tPurchase\n\tPrice\tDate\n"); 30 What does it do? What does this print? prinj("\"Hello!\""); 31 Conversion SpecificaLon Placeholder represenLng a value filled in during prinLng Specifies how a value is converted from its internal (binary) form into characters (printed form) 32 prinj() funcLon (cont.) Basic format specificaLons used in the format string for outpuwng values with prinj ( ) : %d decimal integer %f floaLng point decimal fixed format %e exponenLal floaLng point decimal %g whichever of e or f produces a shorter string %c character %s C string (character array, null terminated) 33 prinj ( ) funcLon (cont.) Ordinary characters are printed as they appear in the format string Conversion specificaLons are matched one-by-one with the remaining arguments : int i = 10, j = 20; double x = 43.2892, y = 5527.0; prinj("i = %d, j = %d, x = %f, y = %f\n", i, j, x, y); What does it print? i = 10, j = 20, x = 43.289200, y = 5527.000000 34 prinj ( ) funcLon (cont.) Warning: C compilers don t check to see if the number of conversion specificaLons in a format string matches the number of output items. (Asuume int i,j and double x) prinj("%d %d\n", i); /* too few values - what happens? */ prinj("%d\n", i, j); /* too many values what happens? */ Furthermore, there s no check that a conversion specificaLon is appropriate for the type of value being printed: prinj("%f %d\n", i, x); /* what happens ? */ 35 printf() Conversion Specifications A ...printf conversion specification consists of the % character, followed by as many as five distinct items: A conversion specification has the form %fm.pX f(optional) indicates left justification default is right justification there are other flags possible here as well m (optional) specifies the minimum field width. .p (optional) specifies: Number of digits after the decimal point (for a floating point number) or Minimum number of digits to print (for an integer) X is the basic data format used (e.g. d,e,f) For a more complete description of conversion specifications see Chapter 22.3 36 ...
View Full Document

This note was uploaded on 02/03/2012 for the course E E 312 taught by Professor Krasner during the Spring '09 term at University of Texas at Austin.

Ask a homework question - tutors are online