- timture.com

Download Report

Transcript - timture.com

HKUST Summer
Programming Course 2008
C++ Control Statements
~ Selection and Iteration
Department of Computer Science and Engineering, HKUST
1
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
2
C++ Control Statements
Introduction
Department of Computer Science and Engineering, HKUST
3
Introduction
 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).
4
C++ Control Statements
Selection Statements
Department of Computer Science and Engineering, HKUST
5
Selection Statements
 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.
6
C++ Control Statements
Selection Statements - if Statement
Department of Computer Science and Engineering, HKUST
7
if Statement
SYNTAX:
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.
8
if Statement
 Remember, only EITHER statement1 or statement2 will be
executed.
true
statement1
expression
false
statement2
 Drawing flowchart is not required in examination.
9
if Statement
 Recall that the else clause is optional.
true
expression
false
statement1
10
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.
11
Example – Absolute Value
#include <iostream>
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;
}
12
Example – Find Larger Number
#include <iostream>
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;
}
13
C++ Control Statements
Selection Statements - Nested ifs Statement
Department of Computer Science and Engineering, HKUST
14
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;/*
else statement 2; /*
else statement 3;
/*
}
else statement 4;
/*
this if is associated*/
with this else */
associated with if(j)*/
associated with if(i)*/
15
Question
 What is the value of c after the following is executed?
#include <iostream>
using namespace std;
int main(){
int a=-1, b=1, c=1;
Answer:
if(a>0)
Value of c: 1
if(b>0)
c = 2;
else
c = 3;
cout << "Value of c: " << c << endl;
return 0;
}
Why?
16
“Dangling Else” Problem
 C++ groups a dangling else with the most recent if.
 The following indentation shows how C++ would
group this example.
#include <iostream>
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;
}
17
“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;
}
18
C++ Control Statements
Selection Statements - if-else-if Ladder Statement
Department of Computer Science and Engineering, HKUST
19
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.
SYNTAX:
if (expression1)
statement1;
else if (expression2)
statement2;
...
else
statementn;
20
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.
21
Example
#include <iostream>
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;
}
22
C++ Control Statements
Selection Statements - ? Operator
Department of Computer Science and Engineering, HKUST
23
? 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
SYNTAX:
expression1 ? expression2 : expression3;
24
? 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.
25
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;
26
Example - Find Larger Number
#include <iostream>
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;
}
27
C++ Control Statements
Selection Statements - switch Statement
Department of Computer Science and Engineering, HKUST
28
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.
SYNTAX:
switch(expression){
case constant1:
statement sequence 1;
break;
case constant2:
statement sequence 2;
break;
…
default:
// optional
statement sequence n;
}
29
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.
30
Example
#include <iostream>
using namespace std;
int main(){
double score;
cout << "Enter a score: ";
cin >> score;
cout << "The letter grade of
switch(int(score)/10){
case 10:
case 9: cout << "Grade =
break;
case 8: cout << "Grade =
break;
case 7: cout << "Grade =
break;
case 6: cout << "Grade =
break;
default: cout << "Grade =
}
return 0;
}
your score: ";
A" << endl;
B" << endl;
C" << endl;
D" << endl;
F" << endl;
31
Example
#include <iostream>
using namespace std;
int main(){
double score;
cout << "Enter a score: ";
cin >> score;
cout << "The letter grade of
switch(int(score)/10){
case 10:
case 9: cout << "Grade =
// break;
case 8: cout << "Grade =
// break;
case 7: cout << "Grade =
break;
case 6: cout << "Grade =
// break;
default: cout << "Grade =
}
return 0;
}
What is the output when
the score is 100, 99, 79,
69, 59?
your score: ";
A" << endl;
B" << endl;
C" << endl;
D" << endl;
F" << endl;
32
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 ifelse-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.
33
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)
34
C++ Control Statements
Selection Statements - Iterative Statements
Department of Computer Science and Engineering, HKUST
35
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
36
C++ Control Statements
Selection Statements - while Statement
Department of Computer Science and Engineering, HKUST
37
while Statement
SYNTAX:
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 nonzero value is true.
 The loop iterates while the expression evaluates to true.
38
while Statement
 How it works:
expression
true
statements
false
 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.
39
Example – Factorial (while-loop)
#include <iostream>
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;
}
40
Example – Compute 2N (while-loop)
#include <iostream>
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;
}
41
Example – Find Maximum (while-loop)
#include <iostream>
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;
}
42
C++ Control Statements
Selection Statements - for Statement
Department of Computer Science and Engineering, HKUST
43
for Statement
SYNTAX:
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.
44
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.
45
for Statement
 How it works:
for_init
for_expression
false


Execute for_init statement.
While for_expression is true
 Execute statements
 Execute post_expression
true
statements
 statements is either a single
statement or a group of
statements within braces.
post_expression
46
Example – Factorial (for-loop)
#include <iostream>
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;
}
47
Example – Compute 2N (for-loop)
#include <iostream>
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;
}
48
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.
49
C++ Control Statements
Selection Statements - do-while Statement
Department of Computer Science and Engineering, HKUST
50
do-while Statement
SYNTAX:
do statements;
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 nonzero value is true.
 The loop iterates while the expression evaluates to true.
51
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.
52
do-while Statement
 How it works:
statements
true
 Execute statements.
 if expression is true then
execute statements again.
 Repeat this process until
expression evaluates to
false.
expression
false
 statements is either a single
statement or a group of
statements within braces.
53
Example – Factorial (do-while loop)
#include <iostream>
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;
}
54
Example – Compute 2N (do-while loop)
#include <iostream>
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;
}
55
Example – Find Maximum (do-while loop)
#include <iostream>
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;
}
56
C++ Control Statements
Selection Statements - Nested Loops
Department of Computer Science and Engineering, HKUST
57
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.
58
Example – Multiplication Table
#include <iostream>
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;
}
59
Example – Find Average Score
#include <iostream>
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;
}
60
C++ Control Statements
Selection Statements - Which Loop to Use?
Department of Computer Science and Engineering, HKUST
61
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.
62
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.
63
C++ Control Statements
Selection Statements – Final Reminder
Department of Computer Science and Engineering, HKUST
64
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.
65
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
66
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
67
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
68