This preview shows page 1. Sign up to view the full content.
Unformatted text preview: Announcements Assignment 2 posted today Assignment 2 posted today Quizzes C Coding Style C C di S l For today: Finish looping control statements (Chap. 6) More on types (Chap. 7) For loop The for statement has the form
for ( expression1 ; expression2 ; expression3 ) statement The following code has the equivalent semantics of the above for statement:
expression1; while ( hil (expression2) i 2) { statement expression3; } For example
for (i = 10; i > 0; i ) printf("T minus %d and counting\n", i) i tf("T i d ti \ " i); Any or all of the three expressions may be omitted Omitting the middle expression creates an infinite loop. g p p Used for counter controlled loops
2 for Loop Semantics
expr1 Initialize counter variable e p expr2 check the condition T Perform the statement(s) in the loop body loop exit expr3 Adjust the counter variable F for Loop examples
/* print out the even numbers from 2 to 100 */ int i; for (i = 2; i<=100; i = i + 2) for (i = 2; i<=100; i = i + 2) { printf ("i is = %d\n",i); } /* print out the squares and sum them all up */ int i, sum=0; for (i = 1; i<=100; i++) { printf ("i squared is = %d\n", i * i); sum = sum + i * i; } printf ("sum of squares is = %d\n",sum); for Loop Semantics
for (i = 1; i<=100; i++) { /* loop body in here */ }
Initialize counter variable i++ Adjust the counter variable i = 1; i <= 100; check the condition T Perform the statement(s) in the loop body p loop exit F What if we need the body of this loop to contain another loop inside of it ? Nested Loops What is the output of the following code? y Can you trace its execution?
int i, num; for (i = 1; i <= 5; i++){ for (num = 0; num < i; num++){ printf ( "%d ", num * 2 + 1); } printf ( "\n"); }
Outer loop p Inner loop Tracing the Code Tracing the Code
Outer l O t loop Inner loop I l Values output V l t t i
1 2 3 4 5 num
0,1 0,1, 2 0,1, 2, 3 0,1, 2, 3, 4 0,1, 2, 3, 4, 5 num * 2 + 1
1 13 135 1357 13579 7 What it does
Terminal Window Options 1 13 135 1357 13579 x 8 The break; Statement
Used to prematurely break out of a loop (or jump out of a switch block)
condition? true Statement(s) break ; Statement(s) false break; Statement Example Statement Example What does this do? What does this do? for( ; ; ) { printf( Enter a number (enter 0 to stop): ); printf("Enter a number (enter 0 to stop): "); scanf("%d", &n); if (n == 0) break; if (n == 0) break; printf("%d cubed is %d\n", n, n*n*n); } Another example Another example What does this do? What does this do? for(d = 2; d<n; d++) { if(n % d == 0) break; if(n % d == 0) break; } if(d < n) if(d < n) printf("%d is divisible by %d\n", n, d); else printf("%d is prime\n"); The continue; Statement
used as a short cut to the bottom of th b tt f the loop or other block (skip the rest of body for that iteration)
false condition? true Statement(s) continue ; Statement(s) continue; Statement Example Statement Example What does this do? What does this do? n = 0; sum = 0; ; while (n < 10) { scanf("%d", &i); if (i == 0) continue; sum = sum + i; n++; } How might we rewrite it How might we rewrite it to be clearer? n = 0; ; sum = 0; while (n < 10) { scanf("%d", &i); if(i != 0){ sum = sum + i; sum sum + i; n++; } } dowhile Statement Th dowhile statement h th f The d hil t t t has the form do statement while ( expression ) ; The do statement works like the while statement except statement, that the expression is evaluated after each execution of the loop. And the loop body is always done at least once. Example: Countdown from 10 This statement can i = 10; be done with a while loop do d { printf("T minus %d and counting\n", i); i; i ; } while (i > 0); Generally avoid using
14 Comma Operator The for statement normally has three expressions The expressions. comma operator allows us to have more than three: ( , ) for (sum = 0, i = 1; i <= N; i++) sum = sum + i; In general, a comma expression has the form expr1 , expr2 expr1 is first evaluated and its value discarded; the value of expr2 is the value of the entire expression. expression The comma operator is handy whenever C requires a single expression, but we'd like to have two or more expressions. p , p In practice, it appears primarily in for statements and macros.
15 Null Statement The ll t t Th null statement is j t a semicolon: t i just i l i = 0; ; j = 1; The null statement is primarily good for one thing: writing loops whose bodies are empty. For example, the statement for (div = 2; div < n; div++) if (n % div == 0) break; Could be rewritten as a loop with an empty body: for (div = 2; div < n && n % div != 0; div++); /* why? */ Accidentally putting a semicolon after the parentheses in an if, while, or for statement will be detected by the compiler as a null statement. if (i < 0); /*logic error */ printf ("Error: i is less than zero\n"); Putting in an extra semicolon creates a common logic error 16 How about this nested loop ?
int i, j, k; for (i = 1; i<=10; i++) { for (j = 1; j<=10; j++) { for (k = 1; k<=10; k++) { ( ; ; ) printf ("the value is: %d\n", i*j*k); } } }
How many times is the printf statement executed? What does the output look like? 17 What is an Algorithm? A procedure (i.e. a sequence of steps/instructions) for solving a problem Must be correct complete unambiguous terminating "executable"(by the Must be correct, complete, unambiguous, terminating, executable (by the execution agent) and understandable. May be transformed into a program if its computable Will typically use abstraction to make the solution clearer and implementation easier May be represented in several ways: May be represented in several ways: Pseudocode structured English language used to help design an algorithm (free form; e.g. recipe) Flowchart a graphical representation; shows control and data flow f Formal languages outside the scope of this course A problem may be solvable by a number of algorithms A problem may be solvable by a number of algorithms Algorithms tend to dictate solution procedures Switching Gears... More on Types Why is Typing Important? Safety prevents meaningless or invalid code ( Hello World / 3) ("Hello World" / 3) Optimization known sizes can support compiler optimizations compiler optimi ations Documentation shows the intended data types of the programmer Abstraction can build higher level types from lower level types (not really in C) 20 You have used the numeric types
int main(void) { int i, j; int numDays; float speed; double distance; scanf( %d%f%lf &numDays &speed &distance); scanf("%d%f%lf",&numDays, &speed, &distance); numDays = distance / speed; printf("Speed = %10.3f Distance = %10.3f Time = %7d", speed, distance, numDays); Ti % 7d" d di t D ) return 0; }
21 <limits.h>
#define SHRT_MIN (32768) /* minimum (signed) short value */ #define SHRT_MAX 32767 /* maximum (signed) short value */ #define USHRT_MAX 0xffff /* maximum unsigned short value */ #define INT_MIN ( 2 d fi (2147483647 1) 836 ) /* minimum (signed) int value */ /* i i ( i d) i l */ #define INT_MAX 2147483647 /* maximum (signed) int value */ #define UINT_MAX 0xffffffff /* maximum unsigned int value */ ( ) / /* minimum (signed) long value */ ( g ) g / #define LONG_MIN (2147483647L 1) #define LONG_MAX 2147483647L /* maximum (signed) long value */ #define ULONG_MAX 0xffffffffUL /* maximum unsigned long value */ #define LLONG_MAX 9223372036854775807i64 /* maximum signed long long int value */ #define LLONG_MIN (9223372036854775807i64 1) /* d f ( ) /* minimum signed long long int value */ dl l l */ #define ULLONG_MAX 0xffffffffffffffffui64 /* maximum unsigned long long int value */ Preprocessor time names (macros) for the minimum and maximum values that can be stored for integer data types
22 <float.h>
#define DBL_DIG 15 #define DBL_EPSILON 2.2204460492503131e016 #define DBL_MANT_DIG 53 #define DBL_MAX 1.7976931348623158e+308 #define DBL_MAX_10_EXP 308 #define DBL_MAX_EXP 1024 #define DBL_MIN #define DBL MIN 2.2250738585072014e308 2 2250738585072014e 308 #define DBL_MIN_10_EXP (307) #define DBL_MIN_EXP (1021) #define _DBL_RADIX 2 #define _DBL_ROUNDS 1 #define FLT_DIG 6 #define FLT_EPSILON 1.192092896e07F #define FLT_GUARD 0 #define FLT_MANT_DIG 24 #define FLT_MAX 3.402823466e+38F #define FLT_MAX_10_EXP 38 #define FLT_MAX_EXP 128 #define FLT_MIN 1.175494351e38F #define FLT_MIN_10_EXP (37) #define FLT_MIN_EXP (125) #define LDBL_DIG DBL_DIG #define LDBL_EPSILON DBL_EPSILON #define LDBL EPSILON DBL EPSILON #define LDBL_MANT_DIG DBL_MANT_DIG #define LDBL_MAX DBL_MAX #define LDBL_MAX_10_EXP DBL_MAX_10_EXP #define LDBL_MAX_EXP DBL_MAX_EXP _ _ #define LDBL_MIN DBL_MIN #define LDBL_MIN_10_EXP DBL_MIN_10_EXP #define LDBL_MIN_EXP DBL_MIN_EXP #define _LDBL_RADIX DBL_RADIX #define _LDBL_ROUNDS DBL_ROUNDS /* # of decimal digits of precision */ /* smallest such that 1.0+DBL_EPSILON != 1.0 */ /* # of bits in mantissa */ /* max value */ /* max decimal exponent */ /* max binary exponent */ /* min positive value */ /* min positive value */ /* min decimal exponent */ /* min binary exponent */ /* exponent radix */ /* addition rounding: near */ / /* # of decimal digits of precision */ g p / /* smallest such that 1.0+FLT_EPSILON != 1.0 */ /* # of bits in mantissa */ /* max value */ /* max decimal exponent */ /* max binary exponent */ /* min positive value */ /* min decimal exponent */ /* min binary exponent */ /* # of decimal digits of precision */ / smallest such that 1 0+LDBL EPSILON != 1 0 / /* smallest such that 1.0+LDBL_EPSILON != 1.0 */ /* # of bits in mantissa */ Preprocessor time names /* max value */ /* max decimal exponent */ (macros) for the /* max binary exponent */ characteristics of / /* min positive value */ p / values that can be stored for /* min decimal exponent */ floating point data types /* min binary exponent */ /* exponent radix */ /* addition rounding: near */ 23 Integer I/O Nuances reading/writing unsigned
/* use the u code for unsigned */ scanf("%u", &z) /* reads z in base 10 unsigned */ printf("%u", z) /* writes z in base 10 unsigned */ reading/writing octal:
/* use the x code for hex */ scanf("%o", &z); f("% " & ) /* reads z in base 8*/ /* d i b 8*/ printf("%o", z); /* writes z in base 8*/ reading/writing hexadecimal
/* use the x code for hex */ /* use the x code for hex */ scanf("%x", &z); /* reads z in base 16 */ printf("%x", z); /* writes z in base 16 */ reading/writing shorts: place the prefix h in front of d o u x reading/writing shorts: place the prefix h in front of d, o, u, x short int s; scanf("%hd", &s); reading/writing longs: place prefix l in front of d o u x reading/writing longs: place prefix l in front of d, o, u, x long int t; printf("%ld", t);
24 Characters char (character) is the remaining basic type for non numeric data What do we do with characters? Input/output them Make bigger strings out of them Break strings into them Compare them h Convert them useful in applications that must deal with f li li i h d l ih strings of text, etc. N Not well supported in C ll di C
25 Character Type usually represented by an 8 bit code p p p dependent upon computer's character set ASCII (7 or 8 bit American Standard Code for Information Interchange) EBCDIC (8 bit Extended Binary Coded Decimal Interchange Code) Unicode (16 bit multilingual) char ch; char ch; ch = `a'; ch = `A'; ch = ` '; C treats characters as small integers C h ll i 26 character `computations'
Mixed with numerics: char ch; int i i = `a'; /* i is now 97 */ ch = 65; ; / /* ch is now `A' */ / ch = ch + 1; /* ch is now `B' */ ch++; /* ch is now `C' */ Used in selection and looping: if (`a' <= ch && ch <= `z') ch = ch ` ' ` ' h h `a' + `A'; ( ; ; ) for (ch = `A'; ch <= `Z'; ch++) { /* loop body */ } Problems Decreases Portability y Assumes knowledge of char set Compiler will not catch Compiler will not catch certain errors Signed or not: signed char sch; unsigned char uch;
27 Escape Sequences p q Escape sequences are also characters:
\a \b \f \n \r \t \v \\ \? \ \" \a \b \f \n \r \t \v \\ \? \' \ Character escapes (like those above) are good for commonly used non keyboard characters commonly used nonkeyboard characters What about the other ones? Numeric escapes: Numeric escapes: Use ASCII table to look up numeric value E.g. "escape" character: Octal escape: \033 (or \33!) Hex escape: \x1b When used as char literal it should be enclosed in single quotes When used as char literal, it should be enclosed in single quotes
#define ESCAPE `\x1b' /* ASCII escape character*/
28 character manipulations
Conversions: C i if (ch >= `a' && ch <= `z') ch = ch `a' + `A'; /* convert it to capital*/ OR #include <ctype.h> /* useful type function library */ ... ch = toupper(ch); /* abstraction, portability */ Reading / Writing Characters (with formatted IO) char ch; h h scanf("%c", &ch); /* reads single character */ scanf(" %c",&ch); /* skips WS, reads single character */ printf("%c", ch); /* writes single character */ do { scanf("%c", &ch); } while (ch != '\n'); /* dumps chars in current line */ 29 Char references Appendix E Ascii character set Unicode: see www.unicode.org Library functions for char type data see pgs 527528 Chapter 23 in general for library support functions for all builtin types 30 ...
View
Full
Document
This note was uploaded on 03/22/2008 for the course EE 312 taught by Professor Shafer during the Spring '08 term at University of Texas at Austin.
 Spring '08
 Shafer

Click to edit the document details