Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 C++ Control Statements ~ Selection and Iteration
2 Overview Introduction Selection Statements if Statement Nested ifs Statement if-else-if Ladder Statement ? Operator switch Statement Iterative Statements while Statement for Statement do-while statement Nested Loops Which Loop to Use? Final Reminder
Department of Computer Science and Engineering, HKUST 3 C++ Control Statements Introduction
4 Up to this point, our programs defined in a function main have had the property that each time they are run, the execution begins with the first statement in the function and proceeds in a straight-line manner to the last statement in the function with every statement along the way being executed once. This kind of programs is able to solve simple problems. However, for general problem we will need to have something more powerful that can control which statements are executed (selection statements or branching statements) and how often (iterative statements or looping statements).
Department of Computer Science and Engineering, HKUST 5 C++ Control Statements Selection Statements
6 Provide ability to control whether a statement list is executed. C++ supports two types of selection statements. if statement switch statement In addition, the ? operator is an alternative to if in certain circumstances.
Department of Computer Science and Engineering, HKUST 7 C++ Control Statements Selection Statements - if Statement
8 if Statement S YNTAX : if (expression) statement1; // executed if expression is true else statement2; // executed if expression is false The else clause is optional. If expression evaluates to true (anything other than 0), statement1 will be executed; otherwise, statement2 will be executed, if it exists.
9 if Statement Remember, only EITHER statement1 or statement2 will be executed. Drawing flowchart is not required in examination. expression statement2 true false statement1
10 if Statement Recall that the else clause is optional. expression true false statement1
11 if Statement Put multiple statements within braces. if (expression){ statements; // executed if expression is true } else{ statements; // executed if expression is false } The else clause is optional.
12 Example – Absolute Value #include using namespace std; int main(){ int value; cout << "Please enter a number: "; cin >> value; if(value < 0) value = -value; cout << "The absolute value of the number is " << value << endl; return 0; }
13 Example – Find Larger Number #include using namespace std; int main(){ int value1, value2, larger; cout << "Enter two integers: "; cin >> value1 >> value2; if(value1 > value2) larger = value1; else larger = value2; cout << "Larger number is: " << larger << endl; return 0; }
Department of Computer Science and Engineering, HKUST 14 C++ Control Statements Selection Statements - Nested ifs Statement
15 Nested ifs Statement A nested if is an if that is the target of another if or else. In a nested if, an else statement always refers to the nearest if statement that is within the same block as the else and that is not already associated with an else. Example: if(i){ if(j) if(k) statement 1;/* this if is associated*/ else statement 2; /* with this else */ else statement 3; /* associated with if(j)*/ } else statement 4;/* associated with if(i)*/
16 Question What is the value of c after the following is executed? #include using namespace std; int main(){ int a=-1, b=1, c=1; if(a>0) if(b>0) c = 2; else c = 3; cout << "Value of c: " << c << endl; return 0; } Answer: Value of c: 1 Why?
17 “Dangling Else” Problem C++ groups a dangling else with the most recent if. The following indentation shows how C++ would group this example. #include using namespace std; int main(){ int a=-1, b=1, c=1; if(a>0) if(b>0) c = 2; else // dangling else grouped to nearest if c = 3; cout << "Value of c: " << c << endl; return 0; }
18 “Dangling Else” Problem Use extra brackets { } to clarify the intended meaning, even if not necessary. This is a good programming practice int main(){ int a=-1, b=1, c=1; if(a>0){ if(b>0) c = 2; else c = 3; } cout << "Value of c: " << c << endl; return 0; }
Department of Computer Science and Engineering, HKUST 19 C++ Control Statements Selection Statements - if-else-if Ladder Statement
20 if-else-if Ladder Statement A common programming construct is the if-else-if ladder, sometimes called the if-else-if staircase because of its appearance. S YNTAX : if (expression1) statement1; else if (expression2) statement2;... else statementn;
21 if-else-if Ladder Statement The conditions are evaluated from the top to the bottom. As soon as a true condition is found, the statement associated with it is executed and the rest of the ladder is BYPASSED. If none of the conditions are true, the last else statement is executed.
22 Example #include using namespace std; int main(){ int score; cout << "Enter a score: "; cin >> score; cout << "The letter grade of your score: "; if(score >= 90) cout << "Grade = A" << endl; else if(score >= 80) cout << "Grade = B" << endl; else if(score >= 70) cout << "Grade = C" << endl; else if(score >= 60) cout << "Grade = D" << endl; else cout << "Grade = F" << endl; return 0; }
Department of Computer Science and Engineering, HKUST 23 C++ Control Statements Selection Statements - ? Operator
24 ? Operator The ? operator can be used to replace if-else statements of the general form: if (expression) statement1; // executed if expression is true else statement2; // executed if expression is false S YNTAX : expression1 ? expression2 : expression3;
25 ? Operator The value of a ? expression is determined as follows. expression1 is evaluated. If it is true, expression2 is evaluated and becomes the value of the entire ? expression. If it is false, expression3 is evaluated and its value and becomes the value of the expression.
26 Example x = 10; y = x>9 ? 100:200; In this example, y is assigned the value 100. If x had been less than or equal to 9, y would have received the value 200. The same code written with the if-else statement would be x = 10; if(x>9) y = 100; else y = 200;
27 Example - Find Larger Number #include using namespace std; int main(){ int value1, value2, larger; cout << "Enter two integers: "; cin >> value1 >> value2; larger = (value1 > value2) ? value1 : value2; cout << "Larger number is: " << larger << endl; return 0; }
Department of Computer Science and Engineering, HKUST 28 C++ Control Statements Selection Statements - switch Statement
29 switch Statement C++ has a built-in multiple branch selection statement, called switch, which successively tests the value of an expression against a list of integral (e.g. int, short, char) compile-time deductible constants. S YNTAX : switch(expression){ case constant1: statement sequence 1; break; case constant2: statement sequence 2; break; … default: // optional statement sequence n; }
30 switch Statement Note that the expression must evaluate to an integral value. Floating-point expressions, for example, are not allowed. No two cases can have the same value. When a match is found, the statements associated with that case is executed until the break statement or the end of the switch statement is reached. Technically speaking, the break statements inside the switch statement are OPTIONAL. When there is no break statement, it will continue to run the code in the next case.
31 Example #include using namespace std; int main(){ double score; cout << "Enter a score: "; cin >> score; cout << "The letter grade of your score: "; switch(int(score)/10){ case 10: case 9: cout << "Grade = A" << endl; break; case 8: cout << "Grade = B" << endl; break; case 7: cout << "Grade = C" << endl; break; case 6: cout << "Grade = D" << endl; break; default: cout << "Grade = F" << endl; } return 0; }
32 Example #include using namespace std; int main(){ double score; cout << "Enter a score: "; cin >> score; cout << "The letter grade of your score: "; switch(int(score)/10){ case 10: case 9: cout << "Grade = A" << endl; // break; case 8: cout << "Grade = B" << endl; // break; case 7: cout << "Grade = C" << endl; break; case 6: cout << "Grade = D" << endl; // break; default: cout << "Grade = F" << endl; } return 0; } What is the output when the score is 100, 99, 79, 69, 59?
33 switch Statement Comparison between switch statements and if-else-if Ladder Statement. Disadvantages of switch statements: The switch statement can only test for equality, whereas if- else-if Ladder Statement can evaluate any type of relational or logical expression. The code size of switch statement is larger. Advantages of switch statements: The code generated from switch statement is sometimes faster (under some conditions). The condition requires a deep understanding of the mechanism of switch, which is not required in the examination.
34 Caution: Assignment operator in expression As mentioned earlier, X=Y and X==Y are both valid expression X==Y is for testing the equality of X and Y X=Y assigns the value of Y to the variable X and returns the value of X That’s why cascading assignments are feasible Therefore, (X = 3) returns 3 and hence it evaluates to true (non-zero) (X = 0) returns 0 and hence it evaluates to false Caution: The meaning of (X=Y) is totally different from (X==Y)
Department of Computer Science and Engineering, HKUST 35 C++ Control Statements Selection Statements - Iterative Statements
36 Iterative Statements C++ provides three types of iterative statements (also called loops) which allow a set of instructions to be executed repeatedly until a certain condition is reached. while statement for statement do-while statement
Department of Computer Science and Engineering, HKUST 37 C++ Control Statements Selection Statements - while Statement
38 while Statement S YNTAX : while(expression) statements; where statements is either an empty statement, single statement, or a block of statements within braces. The expression may be of any expression, and any non- zero value is true. The loop iterates while the expression evaluates to true.
39 while Statement expression statements true false How it works: If expression is true then execute statements. Repeat this process until expression evaluates to false. statements is either a single statement or a group of statements within braces.
40 Example – Factorial (while-loop) #include using namespace std; int main(){ int number, factorial, n; cout << "Enter number: "; cin >> number; factorial = 1; n = 1; while(n <= number){ factorial *= n; n++; } cout << "The factorial of " << number << " is " << factorial << endl; return 0; }
41 Example – Compute 2 N (while-loop) #include using namespace std; int main(){ int number, result, n; cout << "Enter number: "; cin >> number; result = 1; n = 1; while(n <= number){ result *= 2; n++; } cout << "Two raised to the " << number << " power is " << result << endl; return 0; }
42 Example – Find Maximum (while-loop) #include using namespace std; int main(){ int value=0;//input value int max=0;//maximum value while(value!=-1){ cout << "Enter a value (-1 to stop): "; cin >> value; if(value > max) max = value; } cout << "The maximum value found" << " is " << max << endl; return 0; }
Department of Computer Science and Engineering, HKUST 43 C++ Control Statements Selection Statements - for Statement
44 for Statement S YNTAX : for(for_init; for_expression; post_expression) statements; where statements is either an empty statement, a single statement or a group of statements within braces. The for_init is an assignment statement that is used to set the loop control variable. The for_expression is a relational expression that determines when the loop exits. The post_expression defines how the loop control variable changes each time the loop is repeated.
45 for Statement The for loop continues to execute as long as for_expression is evaluated to true. Once the for_expression becomes false, program execution resumes on the statement following the for. Example: for(int i=1; i<=5; i++) cout << "i is " << i << endl; In the loop, i is initially set to 1 and then compared with 5. Since i is less than 5, cout statement is executed and the loop iterate. This causes i to be increased by 1 and again tested to see if it is still less than or equal to 5. If it is, cout statement is called. This process repeats until i is greater than 5, at which point the loop terminates.
46 for Statement for_init for_expression true false statements post_expression How it works: Execute for_init statement. While for_expression is true Execute statements Execute post_expression statements is either a single statement or a group of statements within braces.
47 Example – Factorial (for-loop) #include using namespace std; int main(){ int number, factorial; cout << "Enter number: "; cin >> number; factorial = 1; for(int n=1; n<=number; n++) factorial *=n; cout << "The factorial of " << number << " is " << factorial << endl; return 0; }
48 Example – Compute 2 N (for-loop) #include using namespace std; int main(){ int number, result; cout << "Enter number: "; cin >> number; result = 1; for(int n=1; n<=number; n++) result *= 2; cout << "Two raised to the " << number << " power is " << result << endl; return 0; }
49 Variable Definition in For-loop for(int i=0; i<10; i++) cout << “Hello ” << i; cout << “Printed Hello for “ << i << “times” << endl; The above code is problematic since the variable i cannot be accessed outside the for-loop. It can only be used inside the for-loop.
Department of Computer Science and Engineering, HKUST 50 C++ Control Statements Selection Statements - do-while Statement
51 do-while Statement S YNTAX : dostatements; while(expression); where statements is either an empty statement, single statement, or a block of statements within braces. The expression may be of any expression, and any non- zero value is true. The loop iterates while the expression evaluates to true.
52 do-while Statement Unlike for and while loops, which test the loop condition at the top of the loop, the do-while loop checks its condition at the bottom of the loop. This means that a do-while always executes AT LEAST ONCE.
53 statements expression true false How it works: Execute statements. if expression is true then execute statements again. Repeat this process until expression evaluates to false. statements is either a single statement or a group of statements within braces. do-while Statement
54 Example – Factorial (do-while loop) #include using namespace std; int main(){ int number, factorial, n; cout << "Enter number: "; cin >> number; factorial = 1; n = 1; do{ factorial *= n; n++; }while(n <= number); cout << "The factorial of " << number << " is " << factorial << endl; return 0; }
55 Example – Compute 2 N (do-while loop) #include using namespace std; int main(){ int number, result, n; cout << "Enter number: "; cin >> number; result = 1; n = 1; do{ if(number != 0) result *= 2; n++; }while (n <= number); cout << "Two raised to the " << number << " power is " << result << endl; return 0; }
56 Example – Find Maximum (do-while loop) #include using namespace std; int main(){ int value;//input value int max=0;//maximum value do{ cout << "Enter a value (-1 to stop): "; cin >> value; if(value > max) max = value; }while(value!=-1); cout << "The maximum value found is " << " is “ << max << endl; return 0; }
Department of Computer Science and Engineering, HKUST 57 C++ Control Statements Selection Statements - Nested Loops
58 Nested Loops Nested loops are loops within loops. They are similar in principle to nested if and if-else statements. Many applications require nested loops.
59 Example – Multiplication Table #include using namespace std; int main(){ // Program to output the multiplication table for(int i=1; i<=10; i++){ //Outer loop for(int j=1; j<=10; j++) //Inner loop cout << i*j << " "; cout << endl; } return 0; }
60 Example – Find Average Score #include using namespace std; int main(){ int n, lastassign=8; double avg, score, tscore; char resp; do{ tscore = 0; for(n=1; n<=lastassign; n++){ cout << "Enter student’s score for lab " << n << ": "; cin >> score; tscore += score; } avg = tscore/double(lastassign); cout << "The average score is " << avg << endl; cout << "Enter another student (y/n)? "; cin >> resp; }while(resp=='y' || resp=='Y'); return 0; }
Department of Computer Science and Engineering, HKUST 61 C++ Control Statements Selection Statements - Which Loop to Use?
62 Which Loop to Use? for loop Usually best for sums, products, and counting loops. Especially when you know the number of iterations required. while loop You want to repeat an action without knowing exactly how many times it will be repeated. do-while loop The action should always be executed at least once. Otherwise, the do-while loops and while loops are used in similar situations.
63 Be Careful!! In all three types of loops, if you do not use the brace bracket { } to enclose a block of statements, the loop will only iterate the single statement in the loop. If you put a semi-colon after for-loop, then it will only iterate the null statement (or empty statement). For example, for (int i=0; i<10; i++); cout << “Hello” << endl; It will only print “Hello” once.
Department of Computer Science and Engineering, HKUST 64 C++ Control Statements Selection Statements – Final Reminder
65 Final Reminder To verify an iterative code correct, we normally need to check: The first iteration The second iteration The last iteration If all these are correct, your code is probably correct.
66 break and continue in loop (new slide) Sometimes, we want to stop the execution of a loop in the middle without running to the end break statement is used to stop the execution of other statements below it, and terminate the loop continue statement is used to stop the execution of other statements below it, and continue to the next iteration
67 break and continue in loop for (int i=0; i<3; i++) { cout << “before” << i << “ ”; if ( i == 1 ) break; cout << “after” << i << endl; } Output: before 0 after 0 before 1 If the break is replaced by continue, then the output is before 0 after 0 before 1 before 2 after 2
68 break and continue in loop If break and continue is used in nested loop, they are applied to the innermost loop The outermost loop will continue to run