



















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




















IF-ELSE STATEMENT // Ugly if-else example if (a < b) { c = a * 3; a = b - c; } else a = c + 5; ▪ This code is nice and short but it is hard to read
IF-ELSE STATEMENT // Pretty if-else example if (a < b) { c = a * 3; a = b - c; } else a = c + 5; ▪ This code takes more lines but it is easier to read
NESTED IF STATEMENTS We can have two or more if statements inside each other to check multiple conditions ▪ These are called nested if statements Use indentation to reflect nesting and aid readability ▪ Typically indent 3-4 spaces or one tab Need to take care when matching up { } brackets ▪ This way you can decipher the nesting of conditions
NESTED IF STATEMENTS if ( logical expression1 ) { if ( logical expression2 ) { // Statements to execute if expressions1 and expression2 are true } else { // Statements to execute if expression1 true and expression2 false } } else { // Statements to execute if expression1 false }
NESTED IF STATEMENTS // Ugly nested if example if (a > 0) { if (b < 0) { a = 3 * b; c = a + b; } } else { a = 2 * a; c = b / a; } ▪ It is hard to see what condition the else code goes with
NESTED IF STATEMENTS // Pretty nested if example if (a > 0) { if (b < 0) { a = 3 * b; c = a + b; } } else { a = 2 * a; c = b / a; }
SWITCH STATEMENTS switch ( decision variable ) { case value1 : // Statements to execute if variable equals value break; case value2: // Statements to execute if variable equals value break; ... default: // Statements to execute if variable not equal to any value }
SWITCH STATEMENTS int Number = 0; cin >> Number; switch (Number) { case 0: cout << “This is nothing << endl; break; case 7: cout << “My favorite number” << endl; break;
SWITCH STATEMENTS ▪ The main advantage of switch statement over a sequence of if-else statements is that it is much faster ▪ Jumping to blocks of code is based on a lookup table instead of a sequence of variable comparisons ▪ The main disadvantage of switch statements is that the decision variable must be an integer (or a character) ▪ We can not use a switch with a float or string decision variable or with complex logical expressions