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

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

Goals of this Lecture

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

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

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

Fundamentals of Programming. Lecture 11: C Characters and Strings

LESSON 4. The DATA TYPE char

SWEN-250 Personal SE. Introduction to C

Chapter 8 C Characters and Strings

Chapter 8 - Characters and Strings

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

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

today cs3157-fall2002-sklar-lect05 1

Strings. Steven R. Bagley

LECTURE 15. String I/O and cstring library

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

Contents. Preface. Introduction. Introduction to C Programming

C: How to Program. Week /May/28

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

Program Building. Goals for this Lecture. Help you learn about: Program structure. Detecting and reporting failure

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

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

scanf erroneous input Computer Programming: Skills & Concepts (CP) Characters Last lecture scanf error-checking our input This lecture

CIS 2107 Computer Systems and Low-Level Programming Fall 2011 Midterm

Scientific Programming in C V. Strings

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

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

CS3157: Advanced Programming. Outline

Object Oriented Programming COP3330 / CGS5409

Arrays, Strings, & Pointers

C Fundamentals! C vs. Java: Design Goals. q Java design goals! q Implications for Java! language, machine language, hardware!

THE FUNDAMENTAL DATA TYPES

Characters and Strings

Strings and Library Functions

C mini reference. 5 Binary numbers 12

Computers Programming Course 5. Iulian Năstac

Princeton University Computer Science 217: Introduction to Programming Systems. Assembly Language: Function Calls

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Introduction to string

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

C and Programming Basics

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

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

Tail recursion. Decision. Assignment. Iteration

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

Debugging (Part 1) The material for this lecture is drawn, in part, from The Practice of Programming (Kernighan & Pike) Chapter 5

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

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.

Draft. Chapter 1 Program Structure. 1.1 Introduction. 1.2 The 0s and the 1s. 1.3 Bits and Bytes. 1.4 Representation of Numbers in Memory

The Design of C: A Rational Reconstruction (cont.)

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

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

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

Full file at C How to Program, 6/e Multiple Choice Test Bank

CIS 2107 Computer Systems and Low-Level Programming Fall 2011 Midterm Solutions

The Compilation Process

Princeton University. Computer Science 217: Introduction to Programming Systems. Data Types in C

ch = argv[i][++j]; /* why does ++j but j++ does not? */

These are reserved words of the C language. For example int, float, if, else, for, while etc.

6.096 Introduction to C++ January (IAP) 2009

Appendix A Developing a C Program on the UNIX system

C PROGRAMMING. Characters and Strings File Processing Exercise

The Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford!

Program Verification! Goals of this Lecture! Words from the Wise! Testing!

Chapter 7 C Pointers

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

Multiple Choice Questions ( 1 mark)

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

SU 2017 May 11/16 LAB 2: Character and integer literals, number systems, character arrays manipulation, relational operator

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

Structured programming

Testing! The material for this lecture is drawn, in part, from! The Practice of Programming (Kernighan & Pike) Chapter 6!

Approximately a Test II CPSC 206

Chapter 2 Basic Elements of C++

CIS 2107 Computer Systems and Low-Level Programming Fall 2010 Midterm

printf( Please enter another number: ); scanf( %d, &num2);

Testing! The material for this lecture is drawn, in part, from! The Practice of Programming (Kernighan & Pike) Chapter 6!

CS102: Variables and Expressions

Strings. Daily Puzzle

Fundamental of Programming (C)

1/25/2018. ECE 220: Computer Systems & Programming. Write Output Using printf. Use Backslash to Include Special ASCII Characters

Fundamental of Programming (C)

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

Fundamentals of Computer Programming Using C

Work relative to other classes

AIR FORCE SCHOOL,BAMRAULI COMPUTER SCIENCE (083) CLASS XI Split up Syllabus (Session ) Contents

Lecture 3. More About C

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Softprocessor SP3: Subprograms and Header

UNIT-I Input/ Output functions and other library functions

program structure declarations and definitions expressions and statements more standard I/O

In this Chapter, we tie up some loose ends concerning some of the built in functions provided

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

C Language, Token, Keywords, Constant, variable

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

Fundamentals of Programming

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Assembly Language: Function Calls

Transcription:

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

Goals of this Lecture Help you learn about: The basics of C Deterministic finite-state automata (DFA) Expectations for programming assignments Why? Help you get started with Assignment 1 Required readings + coverage of programming environment in precepts + minimal coverage of C in this lecture = enough info to start Assignment 1 DFAs are useful in many contexts E.g. Assignment 1, Assignment 7 2

Agenda The charcount program The upper program The upper1 program 3

The charcount Program Functionality: Read all chars from stdin (standard input stream) Write to stdout (standard output stream) the number of chars read stdin Line 1 Line 2 charcount stdout?? 4

iclicker Question Q: What is the output of this program, on this input? stdin Line 1 Line 2 charcount stdout?? A. 10 B. 12 C. 13 D. 14 E. 15

The charcount Program The program: charcount.c #include <stdio.h> /* Write to stdout the number of chars in stdin. Return 0. */ int main(void) { int c; int charcount = 0; c = getchar(); while (c!= EOF) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; 6

charcount Building and Running $ gcc217 charcount.c o charcount $./charcount Line 1 Line 2 ^D 14 $ What is this? What is the effect? 7

charcount Building and Running $ cat somefile Line 1 Line 2 $./charcount < somefile 14 $ What is this? What is the effect? 8

charcount Building and Running $./charcount > someotherfile Line 1 Line 2 ^D $ cat someotherfile 14 What is this? What is the effect? 9

charcount Building and Running in Detail Question: Exactly what happens when you issue the command gcc217 charcount.c o charcount Answer: Four steps Preprocess Compile Assemble Link 10

charcount Building and Running in Detail The starting point charcount.c #include <stdio.h> /* Write to stdout the number of chars in stdin. Return 0. */ int main(void) { int c; int charcount = 0; c = getchar(); while (c!= EOF) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; C language Missing definitions of getchar() and printf() 11

Preprocessing charcount Command to preprocess: gcc217 E charcount.c > charcount.i Preprocessor functionality Removes comments Handles preprocessor directives 12

Preprocessing charcount charcount.c #include <stdio.h> /* Write to stdout the number of chars in stdin. Return 0. */ int main(void) { int c; int charcount = 0; c = getchar(); while (c!= -1) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; Preprocessor removes comment 13

Preprocessing charcount charcount.c #include <stdio.h> /* Write to stdout the number of chars in stdin. Return 0. */ int main(void) { int c; int charcount = 0; c = getchar(); while (c!= EOF) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; Preprocessor replaces #include <stdio.h> with contents of /usr/include/stdio.h Preprocessor replaces EOF with -1 14

Preprocessing charcount The result charcount.i... int getchar(); int printf(char *fmt,...);... int main(void) { int c; int charcount = 0; c = getchar(); while (c!= -1) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; C language Missing comments Missing preprocessor directives Contains code from stdio.h Declarations of getchar() and printf() Missing definitions of getchar() and printf() 15

Compiling charcount Command to compile: gcc217 S charcount.i Compiler functionality Translate from C to assembly language Use function declarations to check calls of getchar() and printf() 16

Compiling charcount charcount.i... int getchar(); int printf(char *fmt,...);... int main(void) { int c; int charcount = 0; c = getchar(); while (c!= -1) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; Compiler sees function declarations So compiler has enough information to check subsequent calls of getchar() and printf() 17

Compiling charcount charcount.i... int getchar(); int printf(char *fmt,...);... int main(void) { int c; int charcount = 0; c = getchar(); while (c!= -1) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; Definition of main() function Compiler checks calls of getchar() and printf() when encountered Compiler translates to assembly language 18

Compiling charcount The result: charcount.s format: main:.section ".rodata".string "%d\n".section ".text".globl main.type main,@function pushq %rbp movq %rsp, %rbp subq $4, %rsp call getchar loop: cmpl $-1, %eax je endloop incl -4(%rbp) call getchar jmp loop endloop: movq $format, %rdi movl -4(%rbp), %esi movl $0, %eax call printf movl $0, %eax movq %rbp, %rsp popq %rbp ret Assembly language Missing definitions of getchar() and printf() 19

Assembling charcount Command to assemble: gcc217 c charcount.s Assembler functionality Translate from assembly language to machine language 20

Assembling charcount The result: charcount.o Machine language version of the program No longer human readable Machine language Missing definitions of getchar() and printf() 21

Linking charcount Command to link: gcc217 charcount.o o charcount Linker functionality Resolve references Fetch machine language code from the standard C library (/usr/lib/libc.a) to make the program complete 22

Linking charcount The result: charcount Machine language version of the program No longer human readable Machine language Contains definitions of getchar() and printf() Complete! Executable! 23

Running charcount Command to run:./charcount < somefile 24

Running charcount Run-time trace, referencing the original C code charcount.c #include <stdio.h> /* Write to stdout the number of chars in stdin. Return 0. */ int main(void) { int c; int charcount = 0; c = getchar(); while (c!= EOF) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; Computer allocates space for c and charcount in the stack section of memory Why int instead of char? 25

Running charcount Run-time trace, referencing the original C code charcount.c #include <stdio.h> /* Write to stdout the number of chars in stdin. Return 0. */ int main(void) { int c; int charcount = 0; c = getchar(); while (c!= EOF) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; Computer calls getchar() getchar() tries to read char from stdin Success returns char (within an int) Failure returns EOF EOF is a special non-char value that getchar() returns to indicate failure 26

Running charcount Run-time trace, referencing the original C code charcount.c #include <stdio.h> /* Write to stdout the number of chars in stdin. Return 0. */ int main(void) { int c; int charcount = 0; c = getchar(); while (c!= EOF) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; Assuming c EOF, computer increments charcount 27

Running charcount Run-time trace, referencing the original C code charcount.c #include <stdio.h> /* Write to stdout the number of chars in stdin. Return 0. */ int main(void) { int c; int charcount = 0; c = getchar(); while (c!= EOF) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; Computer calls getchar() again, and repeats 28

Running charcount Run-time trace, referencing the original C code charcount.c #include <stdio.h> /* Write to stdout the number of chars in stdin. Return 0. */ int main(void) { int c; int charcount = 0; c = getchar(); while (c!= EOF) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; Eventually getchar() returns EOF Computer breaks out of loop Computer calls printf() to write charcount 29

Running charcount Run-time trace, referencing the original C code charcount.c #include <stdio.h> /* Write to stdout the number of chars in stdin. Return 0. */ int main(void) { int c; int charcount = 0; c = getchar(); while (c!= EOF) { charcount++; c = getchar(); printf("%d\n", charcount); return 0; Computer executes return statement Return from main() terminates program Normal execution return 0 or EXIT_SUCCESS Abnormal execution return EXIT_FAILURE 30

Review of Example 1 Input/Output Including stdio.h Functions getchar() and printf() 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: = Increment: ++ Relational: ==!= 31

iclicker Question Q: There are other ways to charcount which is best? A B for (c=getchar(); c!=eof; c=getchar()) charcount++; while ((c=getchar())!= EOF) charcount++; C for (;;) { c = getchar(); if (c == EOF) break; charcount++; D c = getchar(); while (c!=eof) { charcount++; c = getchar();

Agenda The charcount program The upper program The upper1 program 33

Example 2: upper Functionality Read all chars from stdin Convert each lower case alphabetic char to upper case Leave other kinds of chars alone Write result to stdout stdin Does this work? It seems to work. upper stdout DOES THIS WORK? IT SEEMS TO WORK. 34

upper Building and Running $ gcc217 upper.c o upper $ cat somefile Does this work? It seems to work. $./upper < somefile DOES THIS WORK? IT SEEMS TO WORK. $ 35

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 HT LF 16 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 { ~ Partial map Note: Lower case and upper case letters are 32 apart 36

upper Version 1 #include <stdio.h> int main(void) { int c; while ((c = getchar())!= EOF) { if ((c >= 97) && (c <= 122)) c -= 32; putchar(c); return 0; What s wrong? 37

Character Literals Examples 'a' '\n' '\t' '\\' '\'' '\0' the a character 97 on ASCII systems newline 10 on ASCII systems horizontal tab 9 on ASCII systems backslash 92 on ASCII systems single quote 39 on ASCII systems the null character (alias NUL) 0 on all systems 38

upper Version 2 #include <stdio.h> int main(void) { int c; while ((c = getchar())!= EOF) { if ((c >= 'a') && (c <= 'z')) c += 'A' - 'a'; putchar(c); return 0; Arithmetic on chars? What s wrong now? 39

Partial map EBCDIC Extended Binary Coded Decimal Interchange Code 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 NUL HT 16 32 LF 48 64 SP. < ( + 80 &! $ * ) ; 96 - /, % _ >? 112 ` : # @ ' = " 128 a b c d e f g h i { 144 j k l m n o p q r 160 ~ s t u v w x y z 176 192 A B C D E F G H I 208 J K L M N O P Q R 224 \ S T U V W X Y Z 240 0 1 2 3 4 5 6 7 8 9 Note: Lower case not contiguous; same for upper case 40

Character Literals Examples 'a' '\n' '\t' '\\' '\'' '\0' the a character 97 on ASCII systems 129 on EBCDIC systems newline 10 on ASCII systems 37 on EBCDIC systems horizontal tab 9 on ASCII systems 5 on EBCDIC systems backslash 92 on ASCII systems 224 on EBCDIC systems single quote 39 on ASCII systems 125 on EBCDIC systems the null character (alias NUL) 0 on all systems 41

ctype.h Functions $ man islower NAME isalnum, isalpha, isascii, isblank, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit character classification routines SYNOPSIS #include <ctype.h> int isalnum(int c); int isalpha(int c); int isascii(int c); int isblank(int c); int iscntrl(int c); int isdigit(int c); int isgraph(int c); int islower(int c); int isprint(int c); int ispunct(int c); int isspace(int c); int isupper(int c); int isxdigit(int c); These functions check whether c... falls into a certain character class...

ctype.h Functions $ man toupper NAME toupper, tolower - convert letter to upper or lower case SYNOPSIS #include <ctype.h> int toupper(int c); int tolower(int c); DESCRIPTION toupper() converts the letter c to upper case, if possible. tolower() converts the letter c to lower case, if possible. If c is not an unsigned char value, or EOF, the behavior of these functions is undefined. RETURN VALUE The value returned is that of the converted letter, or c if the conversion was not possible.

upper Version 3 #include <stdio.h> #include <ctype.h> int main(void) { int c; while ((c = getchar())!= EOF) { if (islower(c)) c = toupper(c); putchar(c); return 0; 44

iclicker Question Q: Is the if statement really necessary? A. Gee, I don t know. Let me check the man page! #include <stdio.h> #include <ctype.h> int main(void) { int c; while ((c = getchar())!= EOF) { if (islower(c)) c = toupper(c); putchar(c); return 0;

ctype.h Functions $ man toupper NAME toupper, tolower - convert letter to upper or lower case SYNOPSIS #include <ctype.h> int toupper(int c); int tolower(int c); DESCRIPTION toupper() converts the letter c to upper case, if possible. tolower() converts the letter c to lower case, if possible. If c is not an unsigned char value, or EOF, the behavior of these functions is undefined. RETURN VALUE The value returned is that of the converted letter, or c if the conversion was not possible.

iclicker Question Q: Is the if statement really necessary? A. Yes, necessary for correctness. B. Not necessary, but I d leave it in. C. Not necessary, and I d get rid of it. #include <stdio.h> #include <ctype.h> int main(void) { int c; while ((c = getchar())!= EOF) { if (islower(c)) c = toupper(c); putchar(c); return 0;

Review of Example 2 Representing characters ASCII and EBCDIC character sets Character literals (e.g., A or a ) Manipulating characters Arithmetic on characters Functions such as islower() and toupper() 48

Agenda The charcount program The upper program The upper1 program 49

Example 3: upper1 Functionality Read all chars from stdin Capitalize the first letter of each word cos 217 rocks Cos 217 Rocks Write result to stdout stdin cos 217 rocks Does this work? It seems to work. upper1 stdout Cos 217 Rocks Does This Work? It Seems To Work. 50

upper1 Building and Running $ gcc217 upper1.c o upper1 $ cat somefile cos 217 rocks Does this work? It seems to work. $./upper1 < somefile Cos 217 Rocks Does This Work? It Seems To Work. $ 51

upper1 Challenge Problem Must remember where you are Capitalize c in cos, but not o in cos or c in rocks Solution Maintain some extra information In a word vs not in a word 52

Deterministic Finite Automaton Deterministic Finite State Automaton (DFA) isalpha (print uppercase equiv)!isalpha (print) NORMAL!isalpha (print) INWORD isalpha (print) States, one of which is denoted the start state Transitions labeled by chars or char categories Optionally, actions on transitions 53

upper1 Version 1 #include <stdio.h> #include <ctype.h> int main(void) { int c; int state = 0; while ((c = getchar())!= EOF) { switch (state) { case 0: if (isalpha(c)) { putchar(toupper(c)); state = 1; else { putchar(c); state = 0; break; case 1: if (isalpha(c)) { putchar(c); state = 1; else { putchar(c); state = 0; break; return 0;!isalpha isalpha 0 1!isalpha That s a B. What s wrong? isalpha 54

upper1 Toward Version 2 Problem: The program works, but States should have names Solution: Define your own named constants enum Statetype {NORMAL, INWORD; Define an enumeration type enum Statetype state; Define a variable of that type 55

upper1 Version 2 #include <stdio.h> #include <ctype.h> enum Statetype {NORMAL, INWORD; int main(void) { int c; enum Statetype state = NORMAL; while ((c = getchar())!= EOF) { switch (state) { case NORMAL: if (isalpha(c)) { putchar(toupper(c)); state = INWORD; else { putchar(c); state = NORMAL; break; case INWORD: if (isalpha(c)) { putchar(c); state = INWORD; else return 0; { putchar(c); state = NORMAL; break; That s a B+. What s wrong? 56

upper1 Toward Version 3 Problem: The program works, but Deeply nested statements No modularity Solution: Handle each state in a separate function 57

upper1 Version 3 #include <stdio.h> #include <ctype.h> enum Statetype {NORMAL, INWORD; enum Statetype handlenormalstate(int c) { enum Statetype state; if (isalpha(c)) { putchar(toupper(c)); state = INWORD; else { putchar(c); state = NORMAL; return state; int main(void) { int c; enum Statetype state = NORMAL; while ((c = getchar())!= EOF) { switch (state) { case NORMAL: state = handlenormalstate(c); break; case INWORD: state = handleinwordstate(c); break; return 0; enum Statetype handleinwordstate(int c) { enum Statetype state; if (!isalpha(c)) { putchar(c); state = NORMAL; else { putchar(c); state = INWORD; return state; That s an A-. What s wrong? 58

upper1 Toward Final Version Problem: The program works, but No comments Solution: Add (at least) function-level comments 59

Function Comments Function comment should describe what the function does (from the caller s viewpoint) Input to the function Parameters, input streams Output from the function Return value, output streams, (call-by-reference parameters) Function comment should not describe how the function works 60

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 viewpoint 61

upper1 Final Version /*------------------------------------------------------------*/ /* upper1.c */ /* Author: Bob Dondero */ /*------------------------------------------------------------*/ #include <stdio.h> #include <ctype.h> enum Statetype {NORMAL, INWORD; Continued on next page 62

upper1 Final Version /*----------------------------------------------------------*/ /* Implement the NORMAL state of the DFA. c is the current DFA character. Write c or its uppercase equivalent to stdout, as specified by the DFA. Return the next state. */ enum Statetype handlenormalstate(int c) { enum Statetype state; if (isalpha(c)) { putchar(toupper(c)); state = INWORD; else { putchar(c); state = NORMAL; return state; Continued on next page 63

upper1 Final Version /*----------------------------------------------------------*/ /* Implement the INWORD state of the DFA. c is the current DFA character. Write c to stdout, as specified by the DFA. Return the next state. */ enum Statetype handleinwordstate(int c) { enum Statetype state; if (!isalpha(c)) { putchar(c); state = NORMAL; else { putchar(c); state = INWORD; return state; Continued on next page 64

upper1 Final Version /*----------------------------------------------------------*/ /* 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. */ int main(void) { int c; /* Use a DFA approach. state indicates the DFA state. */ enum Statetype state = NORMAL; while ((c = getchar())!= EOF) { switch (state) { case NORMAL: state = handlenormalstate(c); break; case INWORD: state = handleinwordstate(c); break; return 0; 65

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 literals Reasonable max nesting depth 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 66

iclicker Question (to gauge your background for next lecture) Q: Convert binary 101010 into decimal and hex A. 42 decimal, 2A hex B. 48 decimal, 32 hex C. 55 decimal, 3G hex D. I know what this means, but I need a calculator E. Huh? Hex? Is this COS or witchcraft?

Summary The C programming language Overall program structure Control statements (if, while, for, and switch) Character I/O functions (getchar() and putchar()) Deterministic finite state automata (DFA) Expectations for programming assignments Especially Assignment 1 Start Assignment 1 soon! 68

Appendix: Additional DFA Examples 69

Another DFA Example Does the string have nano in it? banano yes nnnnnnnanofff yes banananonano yes bananananashanana no other n n Double circle is accepting state Single circle is rejecting state other n a n o start n na nan nano other a other other 70

Yet Another DFA Example Old Exam Question Compose a DFA to identify whether or not a string is a floating-point literal Valid literals -34 78.1 +298.3-34.7e-1 34.7E-1 7..7 999.99e99 Invalid literals abc -e9 1e + 17.9A 0.38+. 38.38f9 71