View
219
Download
2
Embed Size (px)
Citation preview
Control Statements (II)
Ying Wu Electrical & Computer Engineering
Northwestern [email protected]
ECE230 Lectures Series
Question from last lecture
int c = 5;
int d;
d = (++c) + (++c);
cout << c << endl;
cout << d << endl;
c = 5;
d = (c++) + (c++);
cout << c << endl;
cout << d << endl;
Outline
• Repetition: for
• multiple-selection: switch/case
• Repetition: do/while• break/continue structure
• Structured-programming summery
• Bug-catching
Repetition: for• Flowchart
• The general format when using for loops isfor ( init; ContinuationTest; increment )
statement
• Example: for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
– Prints the integers from one to ten
No semicolon after last statement
counter <= 10 cout << counter << endl;true
false
counter ++
counter = 1
Comparison: for vs. while• for loops can usually be rewritten as while loops:
initialization;
while ( loopContinuationTest){
statement
increment;
}
• Initialization and increment as comma-separated listsfor (int i = 0, j = 0; j + i <= 10; j++, i++)
cout << j + i << endl;
What does this mean?
for( ; ; ){
// statement
}
while(1){
// statement
}
Example (1)• Program to sum the even numbers from 2 to 100
char buffer[500], piece[100];
int st, ed;
st = 1; ed = 5;
for(int i=0;i<=(ed-st);i++)
piece[i] = buffer[st+i];
piece[ed-st+1]= '\0'; // adding a '\0' to end a string
cout << piece;
‘ ‘ ‘v ‘ ‘ a‘ ‘ r‘ ‘ _‘ ‘ 1‘ ‘ ‘ ‘ ‘ ‘ a‘ ‘ ‘ ‘ +‘ ‘ ‘ ‘3‘ ‘ .‘ ‘ 1‘ ‘ 4‘ ‘ ‘ 0
buffer[0]
Example (2) : Search DB
// input: the name of a variable
// output: the corresponding value of the variable
char inName = ‘q’;
char name[500]; double val[100]; int sizeDB = 16;
int index; double res;
for(int i=0;i<sizeDB;i++){
if(name[i] == inName){
index = i;
break;
}
}
res = val[index];
• Program to sum the even numbers from 2 to 100‘a’ ‘b ‘ ‘e‘ ‘t‘ ‘f‘ ‘j‘ ‘p‘ ‘ x‘ ‘m‘ ‘q‘ ‘c‘ ‘y‘ ‘z‘ ‘ o‘ ‘d‘ ‘n‘
name[0]
3 5 3 8 0.5 7.1 0 4.3 3 6.5 9.8 7.9 6 7.2 5.3 3.1
val[0]
Multiple-Selection: switch– Useful when variable or expression is tested for multiple values
– Consists of a series of case labels and an optional default case
true
false
.
.
.
case a case a action(s) break
case b case b action(s) break
false
false
case z case z action(s) break
true
true
default action(s)
Example (1)enum OP {ASN, ADD, MIN, MUL, DIV, INC, DEC}; // define a new enum type
OP op; // given (1) operator (2) operands
double operand_1, operand_2, result;
switch(op){
case ASN: // e.g., a = 1
result = operand_1; break;
case ADD: // e.g., a = b+c
result = operand_1 + operand_2; break;
case MIN: // e.g., a = b-1
result = operand_1 – operand_2; break;
case MUL: // e.g., a = b*c
result = operand_1 * operand_2; break;
case DIV: // e.g., a = b/c
result = operand_1 / operand_2; break;
case INC: // e.g., a ++
result = operand_1 + 1; break;
case DEC:
result = operand_1 – 1; break;
default:
break;
}
1. Initialize variables
2. Input data
2.1 Use switch loop to update count
1 // Fig. 2.22: fig02_22.cpp
2 // Counting letter grades3 #include <iostream>45 using std::cout;6 using std::cin;7 using std::endl;89 int main()10 {11 int grade, // one grade12 aCount = 0, // number of A's13 bCount = 0, // number of B's14 cCount = 0, // number of C's15 dCount = 0, // number of D's16 fCount = 0; // number of F's1718 cout << "Enter the letter grades." << endl19 << "Enter the EOF character to end input." << endl;2021 while ( ( grade = cin.get() ) != EOF ) {2223 switch ( grade ) { // switch nested in while2425 case 'A': // grade was uppercase A26 case 'a': // or lowercase a27 ++aCount; 28 break; // necessary to exit switch2930 case 'B': // grade was uppercase B31 case 'b': // or lowercase b32 ++bCount; 33 break;34
Notice how the case statement is used
2.1 Use switch loop to update count
3. Print results
35 case 'C': // grade was uppercase C36 case 'c': // or lowercase c37 ++cCount; 38 break;3940 case 'D': // grade was uppercase D41 case 'd': // or lowercase d42 ++dCount; 43 break;4445 case 'F': // grade was uppercase F46 case 'f': // or lowercase f47 ++fCount; 48 break;4950 case '\n': // ignore newlines, 51 case '\t': // tabs, 52 case ' ': // and spaces in input53 break;5455 default: // catch all other characters56 cout << "Incorrect letter grade entered."57 << " Enter a new grade." << endl;58 break; // optional59 }60 }6162 cout << "\n\nTotals for each letter grade are:" 63 << "\nA: " << aCount 64 << "\nB: " << bCount 65 << "\nC: " << cCount 66 << "\nD: " << dCount67 << "\nF: " << fCount << endl;6869 return 0;70 }
break causes switch to end and the program continues with the first statement after the switch structure.
Notice the default statement.
Program Output
Enter the letter grades.Enter the EOF character to end input.aBcCAdfCEIncorrect letter grade entered. Enter a new grade.DAb Totals for each letter grade are: A: 3B: 2C: 3D: 2F: 1
Repetition: do/while • The do/while is similar to the while structure,
– Condition for repetition tested after the body of the loop is executed
• Format:do { statement} while ( condition );
• Example (letting counter = 1): do {cout << counter << " ";
} while (++counter <= 10);
– This prints the integers from 1 to 10
• All actions are performed at least once.
true
false
action(s)
condition
break• Causes immediate exit from a while, for, do/while or switch structure
• Program execution continues with the first statement after the structure
• Common uses of the break statement:– Escape early from a loop– Skip the remainder of a switch structure
• Exampleint x;for ( x = 1; x <= 10; x++ ){
if ( x == 5 ) break; cout << x << “ “;
}
will print out 1 2 3 4
continue• Skips the remaining statements in the body of a while, for or do/while structure and proceeds with the next iteration of the loop
• In while and do/while, the loop-continuation test is evaluated immediately after the continue statement is executed
• In the for structure, the increment expression is executed, then the loop-continuation test is evaluated
• Examplefor ( int x = 1; x <= 10; x++ ){
if ( x == 5 ) continue;cout << x << “ “;
}
will print it out 1 2 3 4 6 7 8 9 10
Structured-Programming• Structured programming
– Programs are easier to understand, test, debug and, modify.
• Rules for structured programming– Only single-entry/single-exit control structures are used– Rules:
1) Begin with the “simplest flowchart”.2) Any rectangle (action) can be replaced by two rectangles
(actions) in sequence. 3) Any rectangle (action) can be replaced by any control
structure (sequence, if, if/else, switch, while, do/while or for).4) Rules 2 and 3 can be applied in any order and multiple times.
Structured-Programming
Rule 3
Rule 3Rule 3
Representation of Rule 3 (replacing any rectangle with a control structure)
An unstructured program
Structured-Programming
• All programs can be broken down into– Sequence– Selection
•if, if/else, or switch
• Any selection can be rewritten as an if statement
– Repetition•while, do/while or for• Any repetition structure can be rewritten as a while statement
Exercises
[1] If all variables are integer 5, what are they after– a *= b++;– a /= ++b;
[2] assume i=1, j=2, k=3, m=2, what will happen?cout << ( i == j ) << endl;cout << ( j == 3 ) << endl;cout << ( i >= 1 && j < 4 ) << endl;cout << ( m <= 99 && k < m ) << endl;cout << ( k + m < j || 3 – j >= k ) << endlcout << ( ! m ) << endl;cout << ( !( j – m ) ) << endl;cout << ( !( k > m ) ) << endl;
Bug catching
[1] while ( z >= 0)sum += z;
[2] for ( y=.1; y!=1.0; y += .1) cout << y << endl;
[3] we want to print out 1 to 10. Can we do this:
n = 1;
while ( n < 10 )
cout << n++ <<endl;
[5] int x = 1, total;
while ( x <= 10){
total += x;
++x;
}
For fun!
• How to print out
* *** ***** **************** ******* ***** *** *
A solution• Observation “4 3 2 1 0 1 2 3 4”, “1 3 5 7 9 7 5 3 1”• Building blocks: print_char(int n, char c)
int h = 9/2, m, n;for ( int k=0; k<9; k++){
m = abs(h-k);n = 2*(h-m) + 1;print_char(m, ‘ ‘);print_char(n, ‘*’);cout << endl;
}
• Generalization– any size– odd and even number