I. statements (HR A.13) A. syntax 1. overview ----------------------- KINDS OF STATEMENTS expression: cout << 4; declaration: int count = 7; extern double cos(double); empty: ; compound: x = 1; y = 2; block: { int i; i = x + y; x = i; } control: if (alpha == 3) { cout << "it's 3\n"; } ----------------------- ---------------------------- SYNTAX NOTES Statements end in semicolon Generally don't put a semicolon after } but do put a semicolon before } { int i; i = x + y; x = i; } ---------------------------- any question about the details? 2. reading a grammar (HR 6.2, HR Appendix K, DD Appendix A) -------------------------- READING A BNF GRAMMAR Example rules: ::= 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ::= 0 | ::= | ::= -------------------------- can you give some examples of these? ------------------------------ STATEMENT GRAMMAR (A SUBSET OF C++) ::= | | ; | ; | | while ( ) { } | do { } while ( ) ; | for ( ; ){ } | break ; | continue ; | | return ; | return ; ------------------------------- -------------------------------- ::= if ( ) { } | if ( ) { } else { } | if ( ) { } else -------------------------------- ------------------------------- ::= { } ::= | ::= ::= switch ( ) { } | switch ( ) { } ::= | ::= break ; ::= | ::= case : ::= default: break ; | default: ------------------------------- -------------------------- EXTENSIONS TO BNF GRAMMARS Headington and Riley optional text: ::= [ ] zero or more repetitions: ::= { } quotation of terminals: ::= "0" | Deitel and Deitel: optional text: ::= opt -------------------------- B. examples of while loops 1. infinite loops ------------------------------ // powers-of-2.C #include int main() { int i = 1; while (1) { cout << i << "\n"; i *= 2; } // ASSERT: false (never get here) } ---------------------- 2. count char types (switch, while, char input, end-of-file) ----------------------- PROBLEM Write a program to count the number of digits, operators (+, -, *, /) and other characters typed as input. ------------------------ a. psuedo-code outline b. first draft c. commentary on loop initialization (setup) and progress d. C++ details i. cin in tests ii. cin and whitespace iii. side effects in tests and redundancy e. loop body 3. student exercise -------------------------- FOR YOU TO DO Write a program that reads numbers and prints their average. Assume the numbers are type double Assume all inputs are numbers. -------------------------- C. for loops 1. example ------------------------- PROBLEM Write a program that inputs two integers, x and y, with y>0, and outputs x to the y power. ------------------------- a. student exercise --------------------------- FOR YOU TO DO Write a program that inputs an integer n, and outputs sum from 1 to n of 1/(n^2 + 1). Use double precision numbers, and a for loop. --------------------------- D. do loops 1. example (if time) E. break and continue in loops 1. example (if time)