lecture04-controlstmts1

lecture04-controlstmts1 - Announcements For today Chapter 3...

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: Announcements For today: Chapter 3, Chapter 5 For Wednesday: Chapter 5 and 6 For next week: Chapter 7 (Types) and 8 (Arrays) Assignment 2 is posted on Blackboard Due on Wednesday, Feb. 8th at 11:59PM 1 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 Why use printf and scanf? 3 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 4 ...printf Conversion Specifications Flags (optional; more than one permitted): Flag Meaning + Left-justify within field. Numbers produced by signed conversions always begin with + or -. Space Nonnegative numbers produced by signed conversion are preceded by a space. # Octal numbers begin with 0, nonzero hexadecimal numbers with 0x or 0X. Floating-point numbers always have a decimal point. Trailing zeros aren t removed from numbers printed with the g or G conversion codes. 0 Numbers are padded with leading zeros up to the field width 5 What do they print? prinM( %d , 4); prinM( %2d , 4); prinM( %-2d , 4); prinM( %2.2f , 4.4); prinM( %4.2f , 4.4) prinM( %5.2f , 4.4); prinM( %.0f , 4.4); 4 4 (one space first before 4) 4 (one space last) 4.40 (no spaces) 4.40 (no spaces) 4.40 (one space first) 4 6 Example #include <stdio.h> int main(void) { /* example of forma\ed output */ int i; double f; i = 40; f = 839.21; prinM("|%d|%5d|%-5d|%5.3d|\n", i, i, i, i); prinM("|%10.3f|%10.3e|%-10g|\n", f, f, f); return 0; } /* example output appears as: |40|40|40|040| |839.210|8.392e+02|839.21| */ Escape Sequence \a Alert (bell) \b Backspace \n New Line \t Horizontal Tab \" " \\ \ NOTE: the "e+02" count as 4 characters. 7 The scanf Function "the pattern matching function" scanf ( "Format string in quotes", &variable list) scanf requires a format string, followed by a list of variables into which input is to be stored Each variable must be preceded by & Forgefng to put the & symbol in front of a variable will have unpredictable --and possibly disastrous--results format strings are similar to prinM, but usually contain only conversion specificahons: n n n int i, j; float x, y; scanf("%d%d%f%f", &i, &j, &x, &y); For each conversion spec (L to R), find the next corresponding value in the input stream, and then assign it to the variable The type of variable, conversion spec and the input value should all match 8 Scanf (cont'd) When used with scanf, e, f, and g conversions are idenhcal each causes scanf to read a floahng-point number Use %le to read a double. 9 How scanf works scanf ( ) scans each character in the input stream when searching for an input item to match a format code. scanf ignores white-space characters (blanks, tabs, and new-line characters) while looking for data items Scanf does not ignore space If scanf is used in the following way: scanf("%d%d%f%f", &i, &j, &x, &y); 1 -20 .3 -4.0e3 when looking for characters in the format string.... We will discuss this in a minute the input could be split over several lines: or put on a single line: 1 -20 .3 -4.0e3 10 How scanf works (cont.) When scanf encounters a character that can t be part of the current item, this character is scanned for the next input item or during the next call of scanf n Given: scanf("%d%d%f%f", &i, &j, &x, &y); If the input is: 1-20.3-4.0e3 i = 1, j = -20, x = 0.3, y = -4.0e3 Aoer reading an integer, scanf skips white-space characters unhl it finds a non-white-space character An interachve program will hang unhl the user enters a nonblank character. 11 The scanf Format String A scanf format string may contain ordinary characters in addihon to conversion specs Non-white-space character must match the next input character or scanf terminates without reading further. (The non-matching character can be read by a later call of scanf.) For example, (int month, day, year;) nscanf("%d/%d/%d", &month, &day, &year); nwill it read? Why or why not? 5/ 28/ 2002 12 The scanf format string (cont'd) A white-space character in a format string matches zero or more white-space characters in the input. The call scanf("%d/%d/%d", &month, &day, &year); will read 5/ 28/2002 and similar inputs, regardless of the amount of space before or aoer each / 13 The scanf Format String (cont.) Pufng a new-line character at the end of a scanf format string is usually a bad idea: scanf("%d\n", &i); Why? space input \n causes scanf to expect white-space Can cause program to hang waihng for non-white- 14 Formatted I/O Pitfalls What s wrong with: prinM( %d %d\n , &i, &j); What s (potenhally) wrong with: scanf( %d, %d , &i, &j); 15 Formatted I/O Pitfalls (cont.) What s (potenhally) wrong with: prinM( %d%d%d\n , 1, 2, 3); 16 Formatted IO Example #include <stdio.h> What would int main( ) happened if the { user did not input /* Name: Jo Programmer, EID = how888 the two "/"s in Sechon: 55555 the input? Assignment: 2x Purpose: a program that prompts and accepts a date from the user in mm/dd/yy format and then displays it in yymmdd format */ int month, day, year; /* declarahon of variables */ prinM ("Enter a date (mm/dd/yy): "); /* a user prompt */ scanf ("%d/%d/%d", &month, &day, &year); prinM ("You entered the date %.2d%.2d%.2d\n", year, month, day); return 0; sample input and output Enter a date (mm/dd/yy): 2/17/96 } You entered the date 960217 17 EE312: SOFTWARE DESIGN AND IMPLEMENTATION I LECTURE 6: CONTROL STATEMENTS Spring 2012 Professor Suzanne Barber [email protected] ACES 5.440 Office Hours: MW 11 am Noon, or by appointment Algorithms and Data Structures Programs are made up of algorithms (implemented as funcEons in C) and data structures (implemented as variables, arrays, etc.) 19 What is an Algorithm? An algorithm is a procedure (i.e., a sequence of steps/instruchons) for solving a problem It must be correct, complete, unambiguous, terminahng, capable of being executed and understandable. A given problem may be solvable by a number of different algorithms An algorithm may be transformed into a working program if its computable An algorithm will typically use levels of abstrachon to make the soluhon clearer and implementahon easier 20 What is an Algorithm? An algorithm may be represented in several ways: Pseudocode - structured English language used to help design an algorithm Flowchart - a graphical representahon of an algorithm. It shows control and data flow. Formal languages - outside the scope of this course 21 How To Shampoo Your Hair Follow these simple steps: Wet your hair Apply shampoo Lather Rinse Repeat 22 How To Shampoo Your Hair Follow these simple steps: Wet your hair Apply shampoo Lather Rinse Repeat Steps 1 - 4 depict a sequenhal flow of instruchons Step 5 introduces the nohon of repehhon/iterahon of instruchons 23 How To Shampoo Your Hair Follow these simple steps: If out of shampoo, then run out and buy some Wet your hair Apply shampoo This is a decision making statement Lather Rinse Repeat 24 How To Shampoo Your Hair Follow these simple steps: Wet your hair Apply shampoo Lather Rinse Repeat steps 1 - 4, if necessary This is a bounded iterahon statement 25 How To Shampoo Your Hair Follow these simple steps: Wet your hair Set the wash hair counter to 0 Repeat steps 3A - 3D while the value of wash hair counter is less than 3 (i.e. do it three hmes) Step 3A: Apply shampoo Step 3B: Lather Step 3C: Rinse Step 3D: Add 1 to the wash hair counter Stop This is what pseudocode looks like 26 How To Shampoo Your Hair start Wet your hair Set the wash hair counter to 0 Is the wash hair counter < 3 ? False stop True Apply shampoo Lather Rinse Add 1 to the wash hair counter This is what a flowchart looks like 27 Program control logic More complex problems require situahonal decision logic that provides alternahve paths of execuhon: n Instruchons done in sequence (what we have seen so far) can be grouped n Selechon among alternahve paths of execuhon n Iterahon/repehhon of a set of instruchons C has several types of statements for implemenhng these capabilihes But first we need to understand these at the program design level 28 Flowchart Symbology 101 - Design Primitives Program start/stop Process step/ function/ action Control flow Decision Point Input/output connector These are used to create a flowchart for algorithm design 29 Three Basic Logic Constructs sequence iteration F condition T condition F selection T ... one or a block of statements grouped together 30 Three Basic Logic Constructs - pseudocode style - Use indentahon to see the block and logic structure iteraOon sequence selecOon 1. ... 2. ... 3.... 1. Repeat below steps while some condihon is true a) ... b) ... c) ... end repeat 2. ... 3. ... 1.If condihon is true then ... else ... end if 2. ... 3. ... Possible condition statements while do for Possible condition statements If Switch 31 Program Control Statements Controlling the flow of the program s logic Selechon - deciding among alternahve execuhon paths Boolean values, variables and logical expressions (T/F) These are condiOons that are tested by your program Using if and if...else statements Nested and cascaded if statements Using switch statements Iterahon - repehhon of statement(s) Looping idioms: while, do, and for statements Nested loops Using break and conhnue statements (uncondihonal jumps) 32 Logical Expressions (relahonal tests) The relahonal operators are: < less than > greater than <= less than or equal >= greater than or equal The value of a relahonal expression is either 1 (if the condihon is true) or 0 (if it is false): 1 < 2 has the value 1 1 > 2 has the value 0 33 Logical Expressions (relahonal tests) The relahonal operators have lower precedence than the arithmehc operators. For example: i + j < k - 1 means (i + j) < (k - 1) What does i < j < k mean if i =1, j=5, k=3 34 Equality Condihons The equality operators are: == equality != inequality The equality operators produce either 1 or 0 as their result. i + j == k - 1 means (i + j) == (k - 1) i + j != k - 1 means (i + j) != (k - 1) 35 Boolean Condihons boolean values true and false do not exist Any expression whose value is not zero is treated as true; any expression whose value is zero is treated as false An integer variable can store a Boolean value (1 to represent true and 0 to represent false): int flag; /* represents a Boolean condihon */ n flag = 1; /* condihon is true */ n To improve readability, it is a good idea to define constants named TRUE and FALSE: #define TRUE 1 n #define FALSE 0 n . . . n flag = FALSE; n 36 Logical Operators The logical operators are logical negahon n&& logical and n|| logical or produce 0 or 1 as their result but are not limited to 0 and 1 !expr is 1 if expr has value 0 expr1 && expr2 is 1 if expr1 and expr2 are both nonzero expr1 || expr2 is 1 if either expr1 or expr2 (or both) is nonzero In all other cases, these operators produce the value 0 n! 37 Logical Operators Both && and || perform short-circuit evaluahon of their operands The following expression is legal even if i has the value 0: n (i != 0) && (j / i > 0) The precedence of && and || is lower than that of the relahonal operators and the equality operators. For example: n i < j && k == m means (i < j) && (k == m) 38 Remember: Three Basic Logic Constructs sequence iteration selection F condition T condition F T ... one or a block of statements grouped together 39 Which construct would you use to describe these situations? Deciding which sweater to buy online When to exit one of your classes Getting ready in the morning Deciding which employer to work for Taking and ending a final exam 40 ...
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.

Ask a homework question - tutors are online