Lecture 01b: C++ review Topics: if's and switch's while and for loops
Part I: Conditionals A means to select (possibly) one of (possibly) many alternative code blocks. – A single statement – Or a block of code surrounded by curly braces If / else structures use a conditional (boolean expression) Switch's are more limited and can only compare the contents of a single (numeric) variable. – They offer no speed advantage – They are uglier than if/else's
if "0 of 1" version if (cond) code-block "1 of n" version if (cond1) code-block1 else if (cond2) code-block2 … else code-blockN "0-1 of n" version Like "1 of n" but without the else "n of m" version if (cond1) code-block1 if (cond2) code-block2 …
Conditions Simple x < 5 y != 3 health == 100.0f// Be careful w/ float's Compound x < 5 && y != 3 !strcmp(s, "ABC") && age < 65
(Ugly) switch statements int x; // x is filled in elsewhere... switch(x) { case 5: code// no need for braces break; case -1: code// note: no break; "fall-through" case -2: code break; default: code// Executed if none of the others break; }
Pitfalls A condition can be a boolean or… – A numeric value (0 = false, non-zero = true) int x; // x is modified if (x) // will be executed if x != 0 { /* … */ } Assignment statements – Are allowable, and are sometimes useful – But…can be an error if you meant to do comparison (==) if (x = 15) {} // Changes x and block is always executed Not enclosing a block in curly braces if (health < 15) speed = 1.2f; activateRage(); // Always executed, regard. of health
Part II: Repetition A way to repeat a code-block (possibly) multiple times 3 variants: – while: executed 0-n times – do-while: executed 1-n times – for: shorthand for common while loops
While int i = 5, x=0; while (i < n && x < 100) { // Do something // Get set up for next iteration i += 2; x += i * i; }
for // Same effect as last slide for (int i = 5, x = 0; i < n && x < 100; i+= 2, x += i * i) { // Do something }
Do-While int choice; do { cout << "Enter choice (9=quit): "; cin >> choice; // Do something else } while (choice != 9);
Break and continue Allow you to modify a loop’s behavior break; // End current iteration + leave loop continue; // End current iteration Technically, neither is necessary – It can simplify the code a bit, though. [Intentionally infinite loops] [Example: total numbers until user enters a negative]
Mini-Lab [FizzBuzz] For points or just for “fun”?