C Examples. Goals of this Lecture. Overview of this Lecture

Similar documents
Reminder. Sign up for ee209 mailing list. Precept. If you haven t received any from ee209 yet Follow the link from our class homepage

o Echo the input directly to the output o Put all lower-case letters in upper case o Put the first letter of each word in upper case

Goals of this Lecture

Princeton University Computer Science 217: Introduction to Programming Systems. Goals of this Lecture. A Taste of C. Agenda.

Princeton University Computer Science 217: Introduction to Programming Systems. A Taste of C

Appendix A Developing a C Program on the UNIX system

LESSON 4. The DATA TYPE char

Data Representation and Binary Arithmetic. Lecture 2

CS341 *** TURN OFF ALL CELLPHONES *** Practice NAME

Fundamentals of Programming. Lecture 11: C Characters and Strings

Chapter 2 Bits, Data Types, and Operations

CPS 104 Computer Organization and Programming Lecture-2 : Data representations,

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

Chapter 8. Characters and Strings

Chapter 2 Bits, Data Types, and Operations

ASSIGNMENT 5 TIPS AND TRICKS

Chapter 2 Bits, Data Types, and Operations

SWEN-250 Personal SE. Introduction to C

today cs3157-fall2002-sklar-lect05 1

Chapter 2 Bits, Data Types, and Operations

Strings. Steven R. Bagley

CS3157: Advanced Programming. Outline

Fundamentals of Programming

Chapter 8 - Characters and Strings

Fundamentals of Programming (C)

Introduction to Decision Structures. Boolean & If Statements. Different Types of Decisions. Boolean Logic. Relational Operators

Lecture (09) x86 programming 8

CS/ECE 252: INTRODUCTION TO COMPUTER ENGINEERING UNIVERSITY OF WISCONSIN MADISON

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Number Systems for Computers. Outline of Introduction. Binary, Octal and Hexadecimal numbers. Issues for Binary Representation of Numbers

CS/ECE 252: INTRODUCTION TO COMPUTER ENGINEERING UNIVERSITY OF WISCONSIN MADISON

Fundamental Data Types

Simple Data Types in C. Alan L. Cox

Do not start the test until instructed to do so!

Chapter 8: Character & String. In this chapter, you ll learn about;

1.1. INTRODUCTION 1.2. NUMBER SYSTEMS

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Chapter 2 Bits, Data Types, and Operations

Data Representa5on. CSC 2400: Computer Systems. What kinds of data do we need to represent?

Data Representa5on. CSC 2400: Computer Systems. What kinds of data do we need to represent?

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

Numbers and Computers. Debdeep Mukhopadhyay Assistant Professor Dept of Computer Sc and Engg IIT Madras

Number Systems Base r

Week 1 / Lecture 2 8 March 2017 NWEN 241 C Fundamentals. Alvin Valera. School of Engineering and Computer Science Victoria University of Wellington

Chapter 8 C Characters and Strings

Bits and Bytes. Data Representation. A binary digit or bit has a value of either 0 or 1; these are the values we can store in hardware devices.

Binary Numbers. The Basics. Base 10 Number. What is a Number? = Binary Number Example. Binary Number Example

Number System (Different Ways To Say How Many) Fall 2016

Chapter 2 Number System

Oberon Data Types. Matteo Corti. December 5, 2001

C: How to Program. Week /May/28

Number Representations

APPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5

Midterm CSE 131 Fall 2014

Chapter 3. Information Representation

Tail recursion. Decision. Assignment. Iteration

Experiment 3. TITLE Optional: Write here the Title of your program.model SMALL This directive defines the memory model used in the program.

Midterm CSE 131 Winter 2013

Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

DATA REPRESENTATION. Data Types. Complements. Fixed Point Representations. Floating Point Representations. Other Binary Codes. Error Detection Codes

Contents. Preface. Introduction. Introduction to C Programming

Connecting UniOP to Datalogic Barcode Readers

Variables and data types

Midterm CSE 131 Winter 2012

Strings and Library Functions

5/17/2009. Digitizing Discrete Information. Ordering Symbols. Analog vs. Digital

Exercises Software Development I. 03 Data Representation. Data types, range of values, internal format, literals. October 22nd, 2014

Number Systems II MA1S1. Tristan McLoughlin. November 30, 2013

Do not start the test until instructed to do so!

Appendix B. Comparison of Bourne Shell and C Shell Constructs. Bourne shell. C shell

CSE 30 Fall 2012 Final Exam

Do not start the test until instructed to do so!

LECTURE 15. String I/O and cstring library

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

Midterm CSE 131 Winter 2014

Characters and Strings

C Libraries. Bart Childs Complementary to the text(s)

CSE 30 Fall 2007 Final Exam

EXPERIMENT 8: Introduction to Universal Serial Asynchronous Receive Transmit (USART)

CSE-1520R Test #1. The exam is closed book, closed notes, and no aids such as calculators, cellphones, etc.

C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018

COS 226 Algorithms and Data Structures Fall Final

EE 109 Unit 3. Analog vs. Digital. Analog vs. Digital. Binary Representation Systems ANALOG VS. DIGITAL

EXPERIMENT 7: Introduction to Universal Serial Asynchronous Receive Transmit (USART)

CMSC 313 Lecture 03 Multiple-byte data big-endian vs little-endian sign extension Multiplication and division Floating point formats Character Codes

Approximately a Test II CPSC 206

C-programming. Goal To give basic knowledge of the C language. Some previous experiences in programming are assumed. Litterature

Fundamentals of Computer Programming Using C

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Midterm CSE 131 Winter 2015

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Midterm Exam, Fall 2015 Date: October 29th, 2015

2a. Codes and number systems (continued) How to get the binary representation of an integer: special case of application of the inverse Horner scheme

CSE 30 Winter 2009 Final Exam

CSE 30 Fall 2013 Final Exam

The Binary Number System

ENCM 339 Fall 2017 Lecture Section 01 Lab 3 for the Week of October 2

Computer Science 217 Final Exam January 25, :30-4:30pm

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Scientific Programming in C V. Strings

Transcription:

C Examples 1 Goals of this Lecture Help you learn about: The fundamentals of C Overall program structure, control statements, character I/O functions Deterministic finite state automata (DFA) Expectations for programming assignments Why? The fundamentals of C provide a foundation for the systematic coverage of C that will follow A power programmer knows the fundamentals of C well DFA are useful in many contexts (e.g. Assignment 1) How? Through some examples 2 Overview of this Lecture C programming examples Echo input to output Convert all lowercase letters to uppercase Convert first letter of each word to uppercase Glossing over some details related to pointers which will be covered subsequently in the course 3 1

Example #1: Echo Problem: Echo input directly to output Program design Include the Standard Input/Output header file (stdio.h) Make declarations of I/O functions available to compiler Allow compiler to check your calls of I/O functions Define main() function int main(int argc, char *argv[]) { Starting point of the program, a standard boilerplate Hand-waving: argc and argv are for input arguments 4 Example #1: Echo (cont.) Program design (cont.) Read a single character Read a single character from the standard input stream (stdin) and return it Write a single character Write a single character to the standard output stream (stdout) 5 Putting it All Together Why int instead of char? Why return a value? 6 2

Read and Write Ten Characters Loop to repeat a set of lines (e.g., for loop) Three expressions: initialization, condition, and increment E.g., start at 0, test for less than 10, and increment per iteration int c, i; Why not this instead: for (i = 1; i <= 10; i++) for (i=0; i<10; i++) { 7 Read and Write Forever Infinite for loop Simply leave the expressions blank E.g., for ( ; ; ) When will this be executed? How would you terminate this program? 8 Read and Write Until End-Of-File Test for end-of-file EOF is a global constant, defined in stdio.h The break statement jumps out of the innermost enclosing loop if (c == EOF) before the loop do some stuff done yet? do more stuff after the loop 9 3

Many Ways to Do the Same Job for (c=getchar(); c!=eof; c=getchar()) while ((c=getchar())!=eof) for (;;) { if (c == EOF) Typical idiom in C, but messy side-effect in loop test while (c!=eof) { Which approach is best? 10 Review of Example #1 Character I/O Including stdio.h Functions getchar() and putchar() Representation of a character as an integer Predefined constant EOF Program control flow The for and while statements The break statement The return statement Operators Assignment operator: = Increment operator: ++ Relational operator to compare for equality: == Relational operator to compare for inequality:!= 11 Example #2: Convert Uppercase Problem: Write a program to convert a file to all uppercase Leave non-alphabetic characters alone Program design: repeat Read a character If unsuccessful, break out of loop If the character is lower-case, convert to uppercase Write the character 12 4

ASCII American Standard Code for Information Interchange 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI 16 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US 32 SP! " # $ % & ' ( ) * +, -. / 48 0 1 2 3 4 5 6 7 8 9 : ; < = >? 64 @ A B C D E F G H I J K L M N O 80 P Q R S T U V W X Y Z [ \ ] ^ _ 96 ` a b c d e f g h i j k l m n o 112 p q r s t u v w x y z { ~ DEL Lower case: 97-122 and upper case: 65-90 E.g., ʻaʼ is 97 and ʻAʼ is 65 (i.e., 32 apart) 13 Implementation in C if (c == EOF) if ((c >= 97) && (c < 123)) c -= 32; 14 Thatʼs a B-minus A good program is: Clean Readable Maintainable Itʼs not enough that your program works! We take this seriously in COS 217 Whatʼs the problem? 97, 123, and 32 are mystery numbers Rationale for them will be lost quickly 15 5

Improvement: Character Constants if (c == EOF) if ((c >= a ) && (c <= z )) c += A - a ; Better; but assumes that alphabetic character codes are contiguous 16 Improvement: Existing Functions Standard C Library Functions NAME ctype(3c) ctype, isdigit, isxdigit, islower, isupper, isalpha, isalnum, isspace, iscntrl, ispunct, isprint, isgraph, isascii - character handling SYNOPSIS #include <ctype.h> int isalpha(int c); int isupper(int c); int islower(int c); int isdigit(int c); int isalnum(int c); int isspace(int c); int ispunct(int c); int isprint(int c); int isgraph(int c); int iscntrl(int c); int toupper(int c); int tolower(int c); DESCRIPTION These macros classify charactercoded integer values. Each is a predicate returning non-zero for true, 0 for false... The toupper() function has as a domain a type int, the value of which is representable as an unsigned char or the value of EOF... If the argument of toupper() represents a lower-case letter... the result is the corresponding upper-case letter. All other arguments in the domain are returned unchanged. 17 Using the ctype Functions #include <ctype.h> if (c == EOF) if (islower(c)) Returns non-zero c = toupper(c); (true) iff c is a lowercase character 18 6

Building and Running % ls upper.c % gcc217 upper.c o upper % ls upper upper.c % upper We ll be on time today! WE LL BE ON TIME TODAY! ^D % 19 Run the Code on Itself % upper < upper.c #INCLUDE <STDIO.H> #INCLUDE <CTYPE.H> INT MAIN(VOID) { INT C; FOR ( ; ; ) { C = GETCHAR(); IF (C == EOF) BREAK; IF (ISLOWER(C)) C = TOUPPER(C); PUTCHAR(C); RETURN 0; 20 Output Redirection % upper < upper.c > junk.c % gcc217 junk.c o junk test.c:1:2: invalid preprocessing directive #INCLUDE test.c:2:2: invalid preprocessing directive #INCLUDE test.c:3: syntax error before "MAIN" etc... 21 7

Review of Example #2 Representing characters ASCII character set Character constants (e.g., ʻAʼ or ʻaʼ) Manipulating characters Arithmetic on characters Functions like islower() and toupper() Compiling and running C code Compile to generate executable file Invoke executable to run program Can redirect stdin and/or stdout 22 Example #3: Capitalize First Letter Capitalize the first letter of each word cos 217 rocks Cos 217 Rocks Sequence through the string, one letter at a time Print either the character, or the uppercase version Challenge: need to remember where you are Capitalize c in cos, but not o in cos or c in rocks Solution: keep some extra information around Whether youʼve encountered the first letter in the word 23 Deterministic Finite Automaton Deterministic Finite Automaton (DFA) Actions are not part of DFA formalism; but theyʼre helpful letter (print uppercase equivalent) not-letter (print) 1 not-letter (print) 2 letter (print) States Transitions labeled by characters (or categories) Optionally, transitions labeled by actions 24 8

Implementation Skeleton #include <ctype.h> int main (void) { if (c == EOF) <process one character> 25 Implementation <process one character> = switch (state) { case 1: <state 1 action> case 2: <state 2 action> default: <this should never happen> not-letter letter letter 1 2 not-letter if (isalpha(c)) { putchar(toupper(c)); state = 2; else if (!isalpha(c)) state = 1; 26 Complete Implementation #include <ctype.h> int state=1; if (c == EOF) switch (state) { case 1: if (isalpha(c)) { putchar(toupper(c)); state = 2; else case 2: if (!isalpha(c)) state = 1; 27 9

Running Code on Itself % gcc217 upper1.c -o upper1 % upper1 < upper1.c #Include <Stdio.H> #Include <Ctype.H> Int Main(Void) { Int C; Int State=1; For ( ; ; ) { C = Getchar(); If (C == EOF) Break; Switch (State) { Case 1: If (Isalpha(C)) { Putchar(Toupper(C)); State = 2; Else Putchar(C); Break; Case 2: If (!Isalpha(C)) State = 1; Putchar(C); Break; Return 0; 28 OK, Thatʼs a B Works correctly, but Mysterious integer constants ( magic numbers ) What now? States should have names, not just 1, 2 29 Improvement: Names for States Define your own named constants enum Statetype {NORMAL,INWORD; Define an enumeration type enum Statetype state; Define a variable of that type 30 10

Improvement: Names for States #include <ctype.h> enum Statetype {NORMAL,INWORD; enum Statetype state = NORMAL; if (c == EOF) switch (state) { case NORMAL: if (isalpha(c)) { putchar(toupper(c)); state = INWORD; else case INWORD: if (!isalpha(c)) state = NORMAL; 31 OK, Thatʼs a B+ Works correctly, but No modularity What now? Should handle each state in a separate function 32 Improvement: Modularity #include <ctype.h> enum Statetype {NORMAL,INWORD; enum Statetype handlenormalstate(int c) {... enum Statetype handleinwordstate(int c) {... enum Statetype state = NORMAL; if (c == EOF) switch (state) { case NORMAL: state = handlenormalstate(c); case INWORD: state = handleinwordstate(c); 33 11

Improvement: Modularity enum Statetype handlenormalstate(int c) { enum Statetype state; if (isalpha(c)) { putchar(toupper(c)); state = INWORD; else { state = NORMAL; return state; 34 Improvement: Modularity enum Statetype handleinwordstate(int c) { enum Statetype state; if (!isalpha(c)) state = NORMAL; else state = INWORD; return state; 35 OK, Thatʼs an A- Works correctly, but No comments What now? Should add (at least) function-level comments 36 12

Function Comments A function s comment should: Describe what the function does Describe input to the function Parameters, input streams Describe output from the function Return value, output streams, (call-by-reference parameters) Not describe how the function works 37 Function Comment Examples Bad main() function comment Read a character from stdin. Depending upon the current DFA state, pass the character to an appropriate state-handling function. The value returned by the state-handling function is the next DFA state. Repeat until end-of-file. Describes how the function works Good main() function comment Read text from stdin. Convert the first character of each "word" to uppercase, where a word is a sequence of letters. Write the result to stdout. Return 0. Describes what the function does from callerʼs point of view 38 An A Effort #include <ctype.h> enum Statetype {NORMAL, INWORD; /*------------------------------------------------------------*/ /* handlenormalstate: Implement the NORMAL state of the DFA. */ /* c is the current DFA character. Return the next state. */ /*------------------------------------------------------------*/ enum Statetype handlenormalstate(int c) { enum Statetype state; if (isalpha(c)) { putchar(toupper(c)); state = INWORD; else { state = NORMAL; return state; 39 13

An A Effort /*------------------------------------------------------------*/ /* handleinwordstate: Implement the INWORD state of the DFA. */ /* c is the current DFA character. Return the next state. */ /*------------------------------------------------------------*/ enum Statetype handleinwordstate(int c) { enum Statetype state; if (!isalpha(c)) state = NORMAL; else state = INWORD; return state; 40 An A Effort /*------------------------------------------------------------*/ /* main: Read text from stdin. Convert the first character */ /* of each "word" to uppercase, where a word is a sequence of */ /* letters. Write the result to stdout. Return 0. */ /*------------------------------------------------------------*/ enum Statetype state = NORMAL; /* Use a DFA approach. state indicates the state of the DFA. */ if (c == EOF) switch (state) { case NORMAL: state = handlenormalstate(c); case INWORD: state = handleinwordstate(c); 41 Review of Example #3 Deterministic finite state automaton Two or more states Transitions between states Next state is a function of current state and current character Actions can occur during transitions Expectations for COS 217 assignments Readable Meaningful names for variables and values Modular Multiple functions, each of which does one well-defined job Function-level comments Should describe what function does See K&P book for style guidelines specification 42 14

Another DFA Example Does the string have nano in it? banano yes nnnnnnnanofff yes banananonano yes bananananashanana no n n n a n o S 1 2 3 a F 43 Yet Another DFA Example Question #4 from fall 2005 midterm Identify whether or not a string is a floating-point number Valid numbers -34 78.1 +298.3-34.7e-1 34.7E-1 7..7 999.99e99 Invalid numbers abc -e9 1e + 17.9A 0.38+. 38.38f9 44 Summary Examples illustrating C Overall program structure Control statements (if, while, for, and switch) Character input/output (getchar() and putchar()) Deterministic finite state automata (i.e., state machines) Expectations for programming assignments 45 15

Looking at the Web Page Week 1: 2/1-2/7 Reading (required): C Programming (King) 1, 2,3 Reading (required): Computer Systems (Bryant & O'Hallaron) 1 Reading (recommended): Programming with GNU Software (Loukides & Oram) 1, 2, 3, 4 Lecture 1: (Monday) Introduction; C Overview Precept 1: (Monday/Tuesday) Introduction; The Computing Environment; Program Preparation Lecture 2: (Wednesday) C Examples Precept 2: (Wednesday/Thursday) Unix; Bash; Emacs Week 2: 2/8-2/14 Reading (required): C Programming (King) 4, 5, 6, 7, 14, 15 Reading (recommended): Computer Systems (Bryant & O'Hallaron) 2 Lecture 3: (Monday) The Design of C Precept 3: (Monday/Tuesday) Simple C Programs; C Fundamentals Lecture 4: (Wednesday) The Design of C (cont.) Precept 4: (Wednesday/Thursday) Multi-File C Programs; GDB (Sunday) De-Comment Assignment Due (at 9:00PM) 46 16