Upload
catherine-johns
View
221
Download
0
Embed Size (px)
DESCRIPTION
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 …
Citation preview
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
• Simplex < 5y != 3health == 100.0f // Be careful w/ float's
• Compoundx < 5 && y != 3!strcmp(s, "ABC") && age < 65
(Ugly) switch statementsint x;// x is filled in elsewhere...switch(x){
case 5:code // no need for bracesbreak;case -1:code // note: no break; "fall-through"case -2:codebreak;default:code // Executed if none of the othersbreak;
}
Pitfalls
• A condition can be a boolean or…– A numeric value (0 = false, non-zero = true)int x;// x is modifiedif (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 bracesif (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 iterationi += 2;x += i * i;
}
for
// Same effect as last slidefor (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 behaviorbreak; // End current iteration + leave loopcontinue; // 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”?