Rossella Lau Lecture 3, DCO10105, Semester B,2005-6 DCO10105 Object-Oriented Programming and Design ...
-
date post
19-Dec-2015 -
Category
Documents
-
view
217 -
download
0
Transcript of Rossella Lau Lecture 3, DCO10105, Semester B,2005-6 DCO10105 Object-Oriented Programming and Design ...
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
DCO10105 Object-Oriented Programming and Design
Lecture 3: Control Statements
Selection statements• logical expression, if-else, switch-case, ?:
Repetition statements• for-loop, while-loop, do-while-loop
Good programming practice: indentation
-- By Rossella Lau
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Limitation of sequential statements
Usually, statements are executed one after each other
But many times we require some statements to be executed only for special situations or some statements to be executed some times in order to avoid long coding
...
One after each other
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Control structures
Usually, a high level language, such as Java or C++, supports two other control structures: selection and repetition
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Selection statement and program flow
Selection statement allows to change the sequential flow by passing (skipping) some statements
SelectionStatements
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Logical expression
A series of logical operations or relational operations
A relational operation compares two values >, <, >=, <=, ==, != The values being compared, usually, are in the same type The result will be a boolean value: true (1) or false (0)
Logical operations binary or bit by bit operations: &, | not in this course boolean computation: &&, || , !
• may short-cut some operations
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Examples of logical expressions evaluation
a) (x >= 5) && (x <= 10)
b) (x > 4) && (x < 11)
c) ! (x >=5) i.e., x < 5
d) (x >= 5) && ( x <=10) || (x >= -10) && (x <= -5)
Note: a) and b) are equivalent when x is an integer
Simple is the best E.g., use x < 5 is better than using ! (x >= 5)
using b) is better than a) if x is an integer
Don't be lazy! Use (x >= y) rather than using ( ! (x < y) )
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Short-Circuit Evaluation
E.g., (age > = 21) || (x == 5) When age >= 21, the first expression resulted in true and
no matter what the value of x, the result of the whole logical expression will result in true
Once the first expression resulted in true in a Logical Or operation, the execution stops to evaluate the other expression and “short-circuits” the evaluation and returns a value of true
E.g., (grade == ‘A’) && (x >=7) Similarly, once the first expression resulted in false in a
Logical And operation, the evaluation stops with false
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Special notes for C++ logical expression
In C++, a numeric expression can also be treated as a logical expression used as a condition
if (age – 12) cout << “when age is ” << age << “, it is true”;
if (!(age-12)) cout << “when age is “ << age << “, it is false”;
When the value of a numerical expression is 0, it will be treated as false, any other value, including a NEGATIVE value will be treated as true
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Selection – if statements
Display the amount to charge 100 dollars to people over 12 for a concert ticket.
if ( age > 12 ) cout << 100;
age > 12 display 100true
false
Note that when there is more than one statement to be executed for the if condition, braces should be used to make the statements a block
if ( age > 12 ) { charge = 100 cout << charge;}
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Selection – if-else statement
Display the amount to charge 70 for people under 12 and 100 dollars for people 12 or older for a concert ticket.
if ( age < 12 ) cout << 70;else cout << 100;
The if-else statement causes two branches in a program flow statements of if-else are also called branch statements
age < 12
display 100 display 70
truefalse
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
The only ternary conditional operator ? :
The if-else statement in the previous example can be modified to charge = age < 12 ? 70 : 100; or cout << (age < 12 ? 70 : 100);
This ternary operator, conditional operator, has 3 operands:
First: a logical expression Second is the resulting value if First is true Third is the resulting value otherwise
It makes the program flow more simply – good to use whenever possible
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Nested if-else statements
but charge $60 for a senior citizen (65 or over).
if ( age < 12 ) cout << 70;else if ( age >= 65 ) cout << 60; else cout << 100;
age < 12
display 100
display 70
truefalse
age >= 65
display 60
false true
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Serial if-else statements
Although the previous example is a nested if-else statement, all of the branches work towards checking on the age It is more common to treat it as a serial of if-else statements and its more acceptable to write the code in the following formats:
if ( age < 12 ) cout << 70;else if ( age >= 65 ) cout << 60;else cout << 100;
if ( age < 12 ) cout << 70;elseif ( age >= 65 ) cout << 60;else cout 100;
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
switch-case statementIt is another form of selection statement
It is used more often when there are multiple selections on the same variable
// range() results range of ageswitch ( range (age) ) { case 1: cout << 70; break; case 2: cout << 60; break; default: cout << 100; break; //redundant //but good //style}
age < 12 display 70true
age > 65
false
break
display 60 break
default:display 100
false
true
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Sample coding on exercises
Malik: 4:4 (with structured programming approach) The cost of an international call from New York to New Delhi is calculated as follows: Connection fee, $1.99; $2.00 for the first three minutes; and $0.45 for each additional minute. Write a program that prompts the user to enter the number of minutes the call lasted and outputs the amount due. Format your output with two decimal places.
Use of if-else statement – ch4PEx4a.cpp Use of switch-case statement – ch4PEx4b.cpp Use of conditional operator ?: – ch4PEx4.cpp
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Use if statements when checking on file status
When using cin to get user input, cin may be re-directed to an input file
the input file may not exist there may not be data or sufficient data in the file A simple check on the above two cases can be:if (cin) // cin does not have the above two problems
Similarly, when using an input file stream, one can check, e.g., if (inFile) // input ok or if (!inFile) //input not ok
Example program: Malik: 4 Average test score
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
assert() if (!inFile) {
cout << “Cannot open the input file. ” <<“The program terminates.” << endl; return EXIT_FAILURE; }
can use an alternative way to terminate the program:assert (inFile);
When inFile cannot be opened, the program will terminate with messages:
Assertion failed: inFile, file D:/acadWeb/teaching/04-05/dco10105/lab/lab4/Ch4_AverageTestScore.cpp, line 20
This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
When using assert(), one should have #include <cassert> in the header
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Efficiency concerns – avoid redundancy
Observe that the first and the last statements of each branch are the same they can be moved up or down from the branchesif ( minutes > 3) { sum = CONNECTION_FEE + FIRST_3_MINUTES + (minutes - 3) * ADDITIONAL; return sum;}else { sum = CONNECTION_FEE + FIRST_3_MINUTES; return sum;}
sum = CONNECTION_FEE + FIRST_3_MINUTES;if (minutes > 3) sum += (minutes - 3) * ADDITIONAL;return sum;
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Efficiency concerns – return logical expression
If we add a function to determine if a quadratic equation is solvable, we may have:
However, it is more efficient to return the expression directly
bool isSolvable(double a, double b, double c) { if ( (b * b – 4 * a * c) >= 0 ) return true; else return false;}
bool isSolvable(double a, double b, double c) { return ( (b * b – 4 * a * c) >= 0 );}
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Indentation for selection statement
Proper consistent indentation
Each branch opens a deeper level of its associated selection statements and should have a deeper indentation
Same levels should align on the same column
An indentation usually is 4 spaces
An indentation may also simply be a “Tab” but note that “Tab” may not be “portable” among different editors
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Position of braces for selection statement
Consistent braces usage
It is generally accepted that no braces are used for a single statement of a branch
Positions Open at the same line after an if or else statement or an
independent new line under the first character of “if” or “else”
Close at the same column of the function or the if-else statement on a new line
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
A new problem
Wendy plans to deposit 300 dollars at the beginning of each month into her fixed deposit account. The interest is added to the account and rounded to the nearest cent at the end of each month. Assume that the annual interest rate is 6%.
Write a program to display the total amount she can get back by the end of the year
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
The calculation
// the following data may be input from user double deposit = 300.0; double rate = 0.06; double balance = 0.0;
// The first month balance += deposit; balance += round ( balance * rate / 12.0, 2); // The second month balance += deposit; balance += round ( balance * rate / 12.0, 2 );
…… // repeat the last 2 statements 10 more times
cout << “Wendy can get ” << balance << endl;
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
The solution with loop
// the following data may be input from user double deposit = 300.0; double rate = 0.06; double balance = 0.0;
loop for 12 times balance += deposit; balance += round ( balance * rate / 12.0, 2 ); loopend
cout << “Wendy can get ” << balance << endl;
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Loops in a program
Loop, iteration, or repetition statements allow a program to repeatedly execute a portion of the codes.
When viewing the program flow, an iteration diverts the sequential flow to a previous statement
Back to previous
…
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Initialization Before the loop starts, there should be
preparation Condition
To specify if a loop goes on and the variables to specify this condition are called control variables
Update It updates the control variables of the
condition in order to allow the condition to become false. Otherwise, the loop becomes infinitive
Body The statements being repeatedly
executed are the body of the loop
General structure of a loop
…
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Loop statements
A higher level language usually supports three kinds of loops and they can be easily transformed to each other: for-loop, while-loop, and do-while-loop.
for (initialization; condition; update) { body}
initializationwhile (condition) { body update}
initializationdo { body update} while (condition)
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
The sample loops for Wendy's problem
for ( int i = 0; i < 12; i++ ) { balance += deposit; balance += round ( balance * rate / 12.0 ,0); }
int i = 0;while ( i < 12 ) { balance += deposit; balance += …… i++;}
int i = 0; do { balance += deposit; balance += …… i++;} while ( i < 12 )
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Types of loopsThe loop for the previous application is called counter-
controlled repetition It uses i as the loop control variable to count the number
of times the loop should be executed This can be applied when the number of repeated times is
known before the loop is executed
It is quite common for the number of repeated times not to be known before the loop is executed
sentinel-controlled repetition flag-controlled repetition EOF-controlled repetition
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Sentinel-Controlled repetition
A loop is continuously executed until the loop control variable stores a special value, the sentinel
E.g., a user is allowed to enter radius to cirArea.cpp until -1 is entered (the program is terminated if -1 is entered)
radius = inputRadius(); while (radius != -1) { area = calculateArea(radius); displayResult(radius, area); radius = inputRadius(); } // in cirArea.cpp (v3.0)
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Flag-controlled repetition
The loop control variable of a loop is a boolean and the loop is continuously executed the loop control variable becomes false
E.g., a user can continuously enter the radius until he/she replies ‘N’, for the additional prompt
bool goOn = true;while (goOn) { radius = inputRadius(); area = calculateArea(radius); displayResult(radius, area); goOn = inputContinue(); }//in cirArea.cpp (v3.1)
bool inputContinue() { char prompt; cerr << "Continue?(Y/N):"; cin >> prompt; return prompt == 'Y';
}
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
EOF-controlled repetition
Use EOF as the loop control variable
radius = inputRadius(); while (cin) { area = calculateArea(radius); displayResult(radius, area); radius = inputRadius(); }//in cirArea.cpp (v3.2)
The input can be ended by pressing ctrl-D
Another example: copyFile.cpp
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Which loop statement is to be used?
A suggestion:
If the repeating times of the body is known before it is executed, use for loop.
Otherwise, use
while loop for user input process
do-while loop if the loop body is at least executed once
while loop otherwise
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Indentation and braces for repetition statement
Proper consistent indentation
Each loop body opens a deeper level and should have a deeper indentation
The level of indentation is the same for selection statements
Similar to selection statements, the position of braces It is generally accepted that no braces are used for a single statement
of a branch Open at the same line after for(), do, while() or an independent new
line under the first character of “for”, “while”, or “do” Close at the same column of loop statement on a new line
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Early termination of a loop
A loop may need to be terminated before the condition is failed
Such termination is an (or another) ‘exit’ of a loop
Same as Java, the key word for such branching is ‘break’
The execution after an exit is the statement following the loop
In other words, an exit is an early termination of a loop
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
An example of early termination of a loop
Modify the above problem for printing which month Wendy can get an interest of 50 dollars or more.
double deposit = 300.0;double rate = 0.06;double balance = 0.0;double interest = 0.0;for ( int i = 0; i < 12; i++ ) { balance += deposit; interest += roundAmount ( balance * rate / 12.0 ); if ( interest >= 50.0 ) { stdOut.println("Wendy gets $50 at month"+(i+1)); break; } balance += interest;}
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Early re-start of a loop
A loop body may start the next repeated execution before all the statements in the body are executed.
Such repeating causes a re-start point of a loop.
Same as Java, the key word for such branching is ‘continue’
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
An example of early re-start of a loop
Modify the first problem for finding how much Wendy can get if there is no interest for the first three months.
double deposit = 300.0;double rate = 0.06;double balance = 0.0;
for ( int i = 0; i < 12; i++ ) { balance += deposit; if ( i <= 3 ) { continue; //no interest } balance += roundAmount ( balance * rate / 12.0 );}cout << “Wendy can get " << balance << endl;
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Avoid “continue” and “break”
Although they are supported, it is not recommended to use these two statements as much as possible
It causes more than one exit of a loop and increases difficulty in understanding the program and tracing program logic difficult to debug!
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Summary I – for selection statement
We have studied three kinds of selection statements: if-else, switch-case, and ? :
Selection statements allow a program to divert the flow of handling different states of data
assert() is a convenient way to terminate a program with unexpected intermediate result(s)
Indentation for branch statements significantly affect the readability of a program
For efficiency, redundant statements on different branches should be avoided and logical expression should be returned directly
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Summary II – for repetition statement
Make the four parts (initialization, condition, update, body) of a loop explicit for better maintainability
Make sure to properly initialize loop control variables. Ask question: e.g., start from 0 or 1
Make sure to set up a fail situation for terminating a loop
Make sure the interval of the count of a loop is correct E.g., from 0 to 20 or from 1 to 20?
Minimize the use of ‘continue’ and ‘break’ in a loop body
Indent the loop body
Rossella Lau Lecture 3, DCO10105, Semester B,2005-6
Reference
Malik: 4-5
Programming styles: http://personal.cityu.edu.hk/~dcrosela/teaching/04-05/dco1
0105/help/style_white.htm
-- END --