EEL3834 Review Session 2011 September 13
From the homework Cast variables to type, don t just assign them to type. It will confuse you later staic_cast<type>(variable) Turn in.cpp file, not.doc,.pdf, etc. Use CONSTANTS Programming Style sheet
Compiler C++ and many other high level languages require a compiler Converts/translates program into machine (object,.obj) code Looks for errors as it goes along Translates C++ into a format the system can understand. Compilers are hardware dependent C++ is playorm independent; it can be used on any operaing system (Windows, Mac, Linux, etc.) EEL3834 Fall 2011 3
Types of Errors Syntax Errors RunIme Errors Logic Errors EEL3834 Fall 2011 4
Syntax Errors ViolaIons of the programming language s grammar rules Misspelled words Forge_ng ; at the end of a line Detected by compiler Compiler tries to guess what you had intended Makes reporing someimes hard to understand EEL3834 Fall 2011 5
RunIme Errors Not caught by compiler Crash program during execuion May not crash it every Ime (very frustraing) Example: User enters 0 for a divisor Triggers divide by zero error Program crashes, someimes without obvious explanaion EEL3834 Fall 2011 6
Logic Errors Mistakes that compile Program doesn t necessarily crash Program produces incorrect results These are mistakes in the underlying algorithm Example: Using = instead of == in Boolean experessions Very hard to find EEL3834 Fall 2011 7
Algorithms A systemaic procedure for solving a problem A sequence of precise instrucions that leads to a soluion Describes what acions are required to solve a problem Examples on board EEL3834 Fall 2011 8
IdenIfiers Variable names, function names, etc Rules Consists of letter, digits, and underscores Must start with letter or underscore Must not start with a digit Do NOT start with _ because compiler uses names like that Must not be a keyword (see Appendix 1 in Savitch)
IdenIfiers cont. IdenIfiers are case sensiive (test is not the same as Test or TEST) No length limit, but best to keep under 32 characters Choose descripive variable names (radius not x, area not y) Use lowercase lehers for one- word variables Capitalize first leher of all words in variable name except first one. studentssleeping, numberofas, totalstudents
Keywords Reserved Words whose meanings cannot be redefined by the user Examples int, double, return, if, while Full list in Appendix 1 of Savitch
Constants const int HOWMANYSTUDENTS = 42; const double PI = 3.14159; const prevents you from accidentally changing the value in code It is used exactly like the number it replaces Always use all CAPS for constant names
Why use constants? Makes the code more understandable What does that number mean again? Where did it come from? Easier to modify code In the example above, if more students come or drop, I only have to change the code in one place Different occurances of the same number may have different meanings, i.e. 42
Simple Variable Types Name Memory Used Size Range Precision short (also called short int) 2 bytes - 32,768 to 32,768 N/A int 4 bytes - 2,147,483,648 to 2,147,483,647 long (also called long int) 4 bytes - 2,147,483,648 to 2,147,483,647 N/A N/A float 4 bytes Approx. 10-38 to 10 38 7 digits double 8 bytes Aprrox. 10-308 to 10 308 15 digits long double 10 bytes Aprrox. 10-4932 to 10 4932 19 digits char 1 byte All ASCII characters N/A bool 1 byte true, false N/A
chars Single byte used to represent an ASCII character ASCII: American Standard Code for InformaIon Interchange Savitch Appendix 3 shows most of the ASCII character set Represented by single quotes: F = 70, f = 102, + = 43, 3 = 51 Note last one!
Choosing Variable Types Always use int unless double required! FloaIng point math is computaionally expensive FloaIng point math has round- off error which can lead to undesirable comparison results On embedded systems, memory is also a major factor (although becoming less of one each day) Not all embedded processors have floaing point capability
Shorthand Operators Operators for self references += AddiIon Assignment i += 4; => i = i+4; - = SubtracIon Assignment i - = 4; => i = i- 4; *= MulIplicaIon Assignment i *= 4; => i = i*4; /= Division Assignment i /= 4; => i = i/4; %= Modulus Assignment i %= 4; => i = i%4;
Increment and Decrement Operators Unity self reference operators ++var Preincrement var++ PosIncrement - - var Predecrement var- - Postdecrement
Increment & Decrement in Subexpressions Don t do it! int n = 2; n = n + (++n); // Which evaluates first? // This is undefined so result can be either 5 or 6
Order of OperaIons Most are left-associative (evaluated left to right) a + b - c + d => ((a + b) - c) + d Exception: Assignment operators are right-associative (evaluated right to left) a = b += c /= 5 => a = (b += (c /= 5))
Escape Characters See Savitch pg 18 \a Alert (bell) \b Backspace \n New Line (Line Feed) \r Carriage return (return to line start) \t Tab \\ Backslash \ Single quote \ Double quote
Boolean Data Type Have two values: true (1) and false (0) Any non- zero value evaluates to true Examples: bool lightson = true; bool lightson = 1; bool lightson = - 300; All of the above set lightson to 1
RelaIonal Operators Return a Boolean value of 0 or 1 < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to!= Not equal to
RelaIonal Examples int x = 8; x!= 4 => true x < 7 => false x >= 8 => true
Logical Operators! NOT && AND OR (this symbol is typically above Enter on the keyboard)
Truth Tables Savitch pg. 48 Display 2.2 AND exp_1 exp_2 exp_1 && exp_2 true true true true false false false true false false false false OR exp_1 exp_2 exp_1 && exp_2 true true true true false true false true true false false false NOT exp!(exp) true false false true
Use Parentheses for Clarity Do NOT do this: m < x < n Is read as (m < x) < n Should be: (m < x) && (x < n)
if- else statements Execute an acion iff a condiion is true, otherwise, execute another acion. If(booleanExpression) { // MulIple lines of stuff } else { // Do something else }
EnumeraIon You can declare your own variable type Similar to int, char, bool, etc. Enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY}; Day day; day = TUESDAY; This is much like bool with true and false being 1 and 0, only with more states Capitalize the first leher of an enumerated type Capitalize the enirety of the valid values The values (e.g. MONDAY) are idenifiers, not strings
EnumeraIon ConInued Each value stored as a CONSTANT integer in memory Each idenifier is assigned a value staring at 0 In code above MONDAY = 0, TUESDAY = 1, WEDNESDAY = 2, THURSDAY = 3, FRIDAY = 4 You can assign different values if desired enum Day { MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY = 15, FRIDAY}; MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3, THURSDAY = 15, FRIDAY = 16 Comparing values MONDAY < TUESDAY returns true
switch DefiniIon: a slender, flexible shoot, rod, etc., used especially in whipping or disciplining [students] Actually, it is a handy way of implemening a long if- else string
switch layout switch(switch-expression) { case value1: statement(s); break; case value2: statement(s); break;... case valuen: statement(s); break; default: statement(s); } // Values cannot include variables // Values must be constants or literals // If no break, the code will continue on // default not required, but recommended to // at least catch errors
switch Example switch(day) { case MONDAY: cout << read for C++ class ; } break; case TUESDAY: cout << come to C++ class ; break; case WEDNESDAY: case 15: cout << Do C++ homework ; break; case FRIDAY: cout << The week is almost over! ; default: cout << It\ s the weekend!!! ;
Methods for creating program 1) What inputs will the program have? 2) What outputs will the program have? 3) What variables will the program need? a) Why it is very good to declare your variables at the top of your function 4) Flow chart the logic 5) Double check the logic 6) Write the program
while while(loopcontinuationcondition) { // Body of loop // Do stuff here } loopconinuaioncondiion is a Boolean expression that is evaluated before each cycle through the loop Each cycle through the loop is called an itera)on
while Example int count = 0; while(count < 3) { cout << \a ; count ++; } // Trace through on board
while Gotchas Beware of infinite loops! Make sure that your exit condiion exists Use ctrl+c to bail out while(count > -4) while(1) Forge_ng the count++; Avoid using == and!= when reasonable There are Imes to use them Generally beher ways than == or!=
do-while Loops Just like while loop except the Boolean condiion is evaluated a,er each cycle do { // Body: Do stuff here } while (loopcontinuationcondition); // Don t forget the trailing ;
The for loop Extremely useful Loops a fixed number of Imes Like while loop, but compacts control variable iniializaion and modificaion for(initialaction; loopcontinuationcondition; afteriterationaction) { } // Body: Do stuff here
Example: Sound alert 3 times for(int i=0; i < 3; i++) { cout << \a ; } // Note no ; after i++)
Which Loop to Use? while and for are pre- test loops Check condiion before first iteraion do- while is a post- test loop Check condiion aer first iteraion Generally can write any loop with any of the loops Use the most intuiive one The one that makes the program flow most clear
Which loop to use? for Best for loops with fixed number of iteraions Good for iniializing control variable while Best for loops with unknown number of iteraions do- while Like while Use where at least 1 iteraion of loop is required
Loop Keywords break Immediately ends ( breaks out of ) current loop or switch statement coninue Ends current iteraion of current loop Loop may coninue to run ConInuaIon condiion is then checked break and coninue are rarely absolutely necessary (some say never) Avoid them if possible coninue can be paricularly hard to read/understand
EXAM ON THURSDAY