IF (DECISION) STATEMENTS Control Structures The if statement The if/else statement Nested ifs The switch statement Control Structures Sequence -- one after another Selection -- take one path or another if if...else switch Iteration -- loop while do...while for The if statement if (expression) { statement-1; statement-2; ... statement-n; } if expression == 0 (false), skip block if expression != 0 (true), execute block if (sum == SIZE) { result = total / SIZE; cout << result << endl; } What if only 1 statement in block? OK --- if (sum == SIZE) result = total / SIZE; Preferred --- if (sum == SIZE) { result = total / SIZE; } Be very careful! if (sum = SIZE) { ... } The if/else statement if (expression) { statement-1; ... statement-m; } else { statement-1; ... statement-n; } if expression != 0 (true), execute 1st block, skip 2nd if expression == 0 (false), skip 1st block, execute 2nd if (sum == SIZE) { result = total / SIZE; cout << result << endl; } else { total += voltage; sum++; } Again, still use {...} if only one statement in either block Nested ifs if (temp > 0) { if (temp >= 100) { cout << "Steam"; } else { cout << "Water"; } } else { cout << "Ice"; } The switch statement If statement has one branch If/else statement has two branches Switch statement has n branches Case statement Selector variable Compared to set of possible matches switch (selector variable) { case value-1: statement-1; ... break; case value-2: statement-1; ... break; ... case value-n: statement-1; ... break; } Selector variable should be int or char -- not float Values must be constants switch (size) { case SMALL: x = s - z; break; case MEDIUM: x = s * z; --y; break; case LARGE: x = s + z; break; } Suppose SMALL is 5, MEDIUM is 10, LARGE is 15 If size is 10, MEDIUM case of statements x = s * z; --y; break; are executed What if leave out break statement? switch (size) { case SMALL: x = s - z; break; case MEDIUM: x = s * z; --y; case LARGE: x = s + z; break; } If size is 10, MEDIUM and LARGE case of statements x = s * z; --y; x = s + z; break; are executed Do you need the last break statement? Not really. But what if you add a new case??? switch (size) { case TINY: case SMALL: x = s - z; break; case REGULAR: case MEDIUM: case NORMAL: x = s * z; --y; case LARGE: x = s + z; break; } What if selector variable matches two cases? Normally goes to first match. What if selector variable does not match any cases? Skips all statements. default used if no other matches switch (size) { case SMALL: x = s - z; break; case MEDIUM: x = s * z; --y; case LARGE: x = s + z; break; default: cout << "Incorrect size." << endl; break; }