coit29222-structured programming lecture week 06
Post on 30-Dec-2015
15 Views
Preview:
DESCRIPTION
TRANSCRIPT
COIT29222 Structured Programming Slide 1
COIT29222-Structured Programming Lecture Week 06
Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4th Ed.), Chapter 2 Textbook (6th Ed.), Chapters 4 & 5
This week, we will cover the following topics:More on Selection
-switch statement -selection (ternary) operators
More on Loops-while vs. do-while-for vs. while-nested loops
COIT29222 Structured Programming Slide 2
Selection statementsWe have been using one C++ selection
statement – if-else. In this class we explore other selection
statements – statements that allow us to perform different tasks, depending on the input data.
switch statementternary operators
COIT29222 Structured Programming Slide 3
if-else – a reviewLet’s start out by reviewing what we know about the if-else
statement.
if statementif (Age < 18){
cout << “A child!“ << endl;}
if-else statementif (Age < 18){
cout << “A child!“ << endl;}else {
cout << “An adult!“ << endl;}
COIT29222 Structured Programming Slide 4
if-else-if statementif (Age < 13){
cout << “A child!“ << endl;}else if ((Age >= 13 ) && (Age <= 17)){
cout << “A teenager!“ << endl;}else{
cout << “An adult!“ << endl;}
COIT29222 Structured Programming Slide 5
Bracesif (Age < 13)
cout << “A child!“ << endl;else if ((Age >= 13 ) && (Age <= 17))
cout << “A teenager!“ << endl;else
cout << “An adult!“ << endl;
Braces are not required if branch has only one statement.We recommend you always use braces in this course. Sometimes we omit them to fit our examples on a slide.
COIT29222 Structured Programming Slide 6
Nested if/elseif (Gender == ‘M’) if (Age < 18) cout << “A male child!“ << endl; else cout << “A man!“ << endl;else if (Age < 18) cout << “A female child!“ << endl; else cout << “A woman!“ << endl;
COIT29222 Structured Programming Slide 7
Nested if/elseif (Gender == ‘M’) if (Age < 18) cout << “A male child!“ << endl; else cout << “A man!“ << endl;else if (Gender == ‘F’) if (Age < 18) cout << “A female child!“ << endl; else cout << “A woman!“ << endl;else cout << “Unknown gender!“ << endl;
COIT29222 Structured Programming Slide 8
Other selection statementsSelection statements allow us to perform different tasks in our programs, depending on the input data.
The if-else statement is the only selection statement we need. However, most programming languages provide other selection statement for convenience.
In C++, the switch statement is an alternative to the if-else-if statement
For example, a menu-driven program might start like this...
COIT29222 Structured Programming Slide 9
Other selection statementsData Processing Application===========================Select from the menu below: 1 – Load input data from disk 2 – Enter input data 3 – Save input data to disk 4 – Process input data 5 – Display output data 6 – Clear input data 0 – Exit Enter your selection ==> 2:
The main function of this program may include the following if-else-if statement...
COIT29222 Structured Programming Slide 10
int MenuSelection = 1;while (MenuSelection != 0){ DisplayMenuAndObtainSelection( MenuSelection ); if ( MenuSelection == 1 ) LoadInputDataFromDisk( InputData ); else if ( MenuSelection == 1 )
EnterInputData( InputData ); else if ( MenuSelection == 3 )
SaveInputDataToDisk( InputData ); else if ( MenuSelection == 4 )
ProcessInputData( InputData, OutputData ); else if ( MenuSelection == 5 )
DisplayOutputData( OutputData ); else if ( MenuSelection == 6 )
ClearInputData( InputData ); else if ( MenuSelection != 0 )
cout << ”Invalid menu selection!";}
Or, we can use a switch statement...
functions
COIT29222 Structured Programming Slide 11
int MenuSelection = 1;while (MenuSelection != 0){ DisplayMenuAndObtainSelection( MenuSelection ); switch ( MenuSelection ) { case 1: LoadInputDataFromDisk( InputData ); break;
case 2: EnterInputData( InputData ); break;
case 3: SaveInputDataToDisk( InputData ); break;
case 4: ProcessInputData( InputData, OutputData ); break;
case 5: DisplayOutputData( OutputData ); break;
case 6: ClearInputData( InputData ); break;
case 0: break; default: cout << ”Unknown menu selection!"; }}
notes: a little easier to read than if-else-if
COIT29222 Structured Programming Slide 12
int MenuSelection = 1;while (MenuSelection != 0){ DisplayMenuAndObtainSelection( MenuSelection ); switch ( MenuSelection ) { case 1: LoadInputDataFromDisk( InputData ); break;
case 2: EnterInputData( InputData ); break;
case 3: SaveInputDataToDisk( InputData ); break;
case 4: ProcessInputData( InputData, OutputData ); break;
case 5: DisplayOutputData( OutputData ); break;
case 6: ClearInputData( InputData ); break;
case 0: break; default: cout << ”Unknown menu selection!"; }}
notes: on break jump to end of switch statement
COIT29222 Structured Programming Slide 13
int MenuSelection = 1;while (MenuSelection != 0){ DisplayMenuAndObtainSelection( MenuSelection ); switch ( MenuSelection ) { case 1: LoadInputDataFromDisk( InputData ); break;
case 2: EnterInputData( InputData ); break;
case 3: SaveInputDataToDisk( InputData ); break;
case 4: ProcessInputData( InputData, OutputData ); break;
case 5: DisplayOutputData( OutputData ); break;
case 6: ClearInputData( InputData ); break;
case 0: break; default: cout << ”Unknown menu selection!"; }}
notes: default handles cases not handled above
COIT29222 Structured Programming Slide 14
The switch statementswitch is a convenient replacement for simple if-else-if statements
However, switch can only be used when the selection depends on the value of a variable of type integer or char (characters are stored as an integer, using ASCII coding system)
switch ( <integer or char variable> ) {...}
COIT29222 Structured Programming Slide 15
The switch statementor, more fully…
switch ( <integer or char variable> ) { case < constant or literal integer or char >: < statements to handle this case> break; : < other cases > : default: < statements to handle cases not handled above> }
notes: must be a variable of type integer or char
COIT29222 Structured Programming Slide 16
The switch statementor, more fully…
switch ( <integer or char variable> ) { case < constant or literal integer or char >: < statements to handle this case> break; : < other cases > : default: < statements to handle cases not handled above> }
notes: integer or char literal or constant – eg: 1, 'A', EXIT
COIT29222 Structured Programming Slide 17
The switch statementor, more fully…
switch ( <integer or char variable> ) { case < constant or literal integer or char >: < statements to handle this case> break; : < other cases > : default: < statements to handle cases not handled above> }
notes: don’t forget the colon
COIT29222 Structured Programming Slide 18
The switch statementor, more fully…
switch ( <integer or char variable> ) { case < constant or literal integer or char >: < statements to handle this case> break; : < other cases > : default: < statements to handle cases not handled above> }
notes: break; is optional
COIT29222 Structured Programming Slide 19
Optional break;?switch ( CharMenuSelection ){ case 'a': case 'A': ProcessSelectionA; break; case 'b': case 'B': ProcessSelectionB; break; :}
COIT29222 Structured Programming Slide 20
Ternary operatorC++ also has a selection operator – an operator that selects between one of two expression, depending on the input data operators are applied to expressions to produce values of interest:
(FahrenheitTemp - 32) / 1.8
Like switch, the ternary operator is simply a convenience – the role it plays can be performed by if-else...
COIT29222 Structured Programming Slide 21
Ternary operator
The following example outputs “Pass” or “Fail”, depending on value of Mark : cout << (( Mark >= 50 ) ? "Pass" : "Fail ");
syntax: (( <condition> ) ? <expression 1> : <expression 2>)
same as: if ( Mark >= 50 ) cout << "Pass"; else cout << "Fail";
if condition is True, expression 1 is evaluated; otherwise, expression 2 is evaluated
COIT29222 Structured Programming Slide 22
More on LoopsWe have been using one C++ repetition (loop)
statement – while while ( <condition> )
{ < while statements >
}
NbrTimesTold = 0;while (NbrTimesTold < NbrTimesToTell){
cout << “ No new taxes!“ << endl;NbrTimesTold = NbrTimesTold + 1;
}
COIT29222 Structured Programming Slide 23
while – a Review
Common looping errors are: loops that fail to stop (continue forever) loops that stop one repetition too early loops that perform one repetition too
many loops that fail to start
Normal while-loop structure is…
COIT29222 Structured Programming Slide 24
while – a Review
< initialise variables in while-condition > while ( <condition> ){ < while statements > < update variables in while-condition > }
NbrTimesTold = 0;while (NbrTimesTold < NbrTimesToTell){
cout << “ No new taxes!“ << endl;NbrTimesTold = NbrTimesTold + 1;
}
COIT29222 Structured Programming Slide 25
Activity
Number = 5;while (Number > 0){ Sum = Sum + Number ; Number = Number - 1 ;} cout << “The sum is “ << Sum << endl;
What will the following code output?
COIT29222 Structured Programming Slide 26
Activity Feedback
Number = 5;while (Number > 0){ Sum = Sum + Number ; Number = Number - 1 ;} cout << “The sum is “ << Sum << endl;
Output depends on initial value of Sumif Sum is zero at start: “The sum is 15”
must always initialise a sum to zero!
COIT29222 Structured Programming Slide 27
Activity
Sum = 0 ;while (Number > 0){ Sum = Sum + Number ; Number = Number - 1;}cout << “The sum is “ << Sum << endl;
What will the following code output?
COIT29222 Structured Programming Slide 28
Activity Feedback
Output depends on initial value of Number
must initialise variables in while condition!
Sum = 0 ;while (Number > 0){ Sum = Sum + Number ; Number = Number - 1;}cout << “The sum is “ << Sum << endl;
COIT29222 Structured Programming Slide 29
Activity
Sum = 0 ;Number = 5;while (Number > 0){ Sum = Sum + Number ; Number++;}cout << “The sum is “ << Sum << endl;
What will the following code output?
COIT29222 Structured Programming Slide 30
Activity Feedback
Loop will never end – an infinite loop
This is a logic error! Always check loop conditions carefully.
Sum = 0 ;Number = 5;while (Number > 0){ Sum = Sum + Number ; Number++;}cout << “The sum is “ << Sum << endl;
COIT29222 Structured Programming Slide 31
while vs do-while
The while statement tests a condition at the start of the loop
The do-while statement tests a condition at the end of the loop
COIT29222 Structured Programming Slide 32
while vs do-while
The while statement tests a condition at the start of the loop
cout << “Select a direction – N,S,E or W ==> “;cin >> Char;while ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’)){ cout << “Invalid direction!” << endl; cout << “Select a direction – N,S,E or W ==> “; cin >> Char;}
COIT29222 Structured Programming Slide 33
do-while loops
If a task must be performed at least once, we can perform the test at the end of the loop using do-whiledo { cout << “Select a direction – N,S,E or W ==> “; cin >> Char; if ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’)) cout << “Invalid direction!” << endl;} while ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’));
COIT29222 Structured Programming Slide 34
Activity
What are advantages and disadvantages of this design (compared to using while)? do { cout << “Select a direction – N,S,E or W ==> “; cin >> Char; if ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’)) cout << “Invalid direction!” << endl;} while ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’));
Can you suggest an improvement?
COIT29222 Structured Programming Slide 35
Activity Feedback
One advantage of do-while is that there is only one copy of prompt and input lines
cout << “Select a direction – N,S,E or W ==> “;cin >> Char;while ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’)){ cout << “Invalid direction!” << endl; cout << “Select a direction – N,S,E or W ==> “; cin >> Char;}
COIT29222 Structured Programming Slide 36
Activity Feedback
One advantage of do-while is that there is only one copy of prompt and input lines
do { cout << “Select a direction – N,S,E or W ==> “; cin >> Char; if ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’)) cout << “Invalid direction!” << endl;} while ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’));
COIT29222 Structured Programming Slide 37
Activity Feedback
One disadvantage of do-while is that the loop condition appears twice
do { cout << “Select a direction – N,S,E or W ==> “; cin >> Char; if ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’)) cout << “Invalid direction!” << endl;} while ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’));
COIT29222 Structured Programming Slide 38
Activity Feedback
One disadvantage of do-while is that the loop condition appears twice
cout << “Select a direction – N,S,E or W ==> “;cin >> Char;while ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’)){ cout << “Invalid direction!” << endl; cout << “Select a direction – N,S,E or W ==> “; cin >> Char;}
COIT29222 Structured Programming Slide 39
Activity Feedback
Repetition of complex loop conditions can be avoided using a Boolean variable… WaitingForDirection = true;do { cout << “Select a direction – N,S,E or W ==> “; cin >> Char; if ((Char != ‘N’) && (Char != ‘S’) && (Char != ‘E’) && (Char != ‘W’)) cout << “Invalid direction!” << endl; else WaitingForDirection = false;} while ( WaitingForDirection );
COIT29222 Structured Programming Slide 40
Activity
Is the following logic OK? Sum = 0 ;do{ cout << “Enter a number (-9 to quit) ==> "; cin >> Number; Sum = Sum + Number;} while (Number != -9);cout << “Sum = “ << Sum;
if not, fix it.
COIT29222 Structured Programming Slide 41
Activity Feedback
The problem with the logic is that it will include –9 in the sum – it should be:
Sum = 0 ;do{ cout << “Enter a number (-9 to quit) ==> "; cin >> Number; if (Number != -9) Sum = Sum + Number;} while (Number != -9);cout << “Sum = “ << Sum; note: you will often see
loop conditions repeated in do-while statements
COIT29222 Structured Programming Slide 42
for vs while cout << “Number of marks in exam ==> “;
cin >> NbrMarks; cout >> “Number of students ==> “ cin >> NbrStudents; NbrLoops = 0;while (NbrLoops < NbrStudents){
cout << “Student’s mark ==> “;cin >> StudentMark;Percentage = 100 * StudentMark / NbrMarks;cout << “ Student’s percentage: “;cout << Percentage;NbrLoops = NbrLoops +1;
}
notes: initialise loop control variable
COIT29222 Structured Programming Slide 43
for vs while cout << “Number of marks in exam ==> “;
cin >> NbrMarks; cout >> “Number of students ==> “ cin >> NbrStudents; NbrLoops = 0;while (NbrLoops < NbrStudents){
cout << “Student’s mark ==> “;cin >> StudentMark;Percentage = 100 * StudentMark / NbrMarks;cout << “ Student’s percentage: “;cout << Percentage;NbrLoops = NbrLoops +1;
}
notes: loop condition
COIT29222 Structured Programming Slide 44
for vs while cout << “Number of marks in exam ==> “;
cin >> NbrMarks; cout >> “Number of students ==> “ cin >> NbrStudents; NbrLoops = 0;while (NbrLoops < NbrStudents){
cout << “Student’s mark ==> “;cin >> StudentMark;Percentage = 100 * StudentMark / NbrMarks;cout << “ Student’s percentage: “;cout << Percentage;NbrLoops++;
}
notes: modify loop control variable (to avoid looping forever)
COIT29222 Structured Programming Slide 45
cout << “Number of marks in exam ==> “; cin >> NbrMarks; cout >> “Number of students ==> “ cin >> NbrStudents; for (NbrLoops = 0; NbrLoops < NbrStudents; NbrLoops++){
cout << “Student’s mark ==> “;cin >> StudentMark;Percentage = 100 * StudentMark / NbrMarks;cout << “ Student’s percentage: “;cout << Percentage;
}
for vs while
notes: initialise loop control variable
COIT29222 Structured Programming Slide 46
cout << “Number of marks in exam ==> “; cin >> NbrMarks; cout >> “Number of students ==> “ cin >> NbrStudents; for (NbrLoops = 0; NbrLoops < NbrStudents; NbrLoops++){
cout << “Student’s mark ==> “;cin >> StudentMark;Percentage = 100 * StudentMark / NbrMarks;cout << “ Student’s percentage: “;cout << Percentage;
}
for vs while
notes: loop condition
COIT29222 Structured Programming Slide 47
cout << “Number of marks in exam ==> “; cin >> NbrMarks; cout >> “Number of students ==> “ cin >> NbrStudents; for (NbrLoops = 0; NbrLoops < NbrStudents; NbrLoops++){
cout << “Student’s mark ==> “;cin >> StudentMark;Percentage = 100 * StudentMark / NbrMarks;cout << “ Student’s percentage: “;cout << Percentage;
}
for vs while
notes: modify loop control variable (to avoid looping forever)
COIT29222 Structured Programming Slide 48
for ( < loop initialisation statement > ; < loop condition > ; < loop completion statement > ){
< for statements >}
for Loop Syntax
notes: parentheses around for clause
COIT29222 Structured Programming Slide 49
for ( < loop initialisation statement > ; < loop condition > ; < loop completion statement > ){
< for statements >}
for Loop Syntax
notes: statement performed once before entering loop for first time
COIT29222 Structured Programming Slide 50
for ( < loop initialisation statement > ; < loop condition > ; < loop completion statement > ){
< for statements >}
for Loop Syntax
notes: semi-colons after loop initialisation and loop condition
COIT29222 Structured Programming Slide 51
for ( < loop initialisation statement > ; < loop condition > ; < loop completion statement > ){
< for statements >}
for Loop Syntax
notes: condition tested at the start of each loop – including the very first loop
COIT29222 Structured Programming Slide 52
for ( < loop initialisation statement > ; < loop condition > ; < loop completion statement > ){
< for statements >}
for Loop Syntax
notes: statement performed at the end of each loop
COIT29222 Structured Programming Slide 53
for Loop Operation
for
loopstatements
loopconditio
n
false
true
loopinitialisestateme
nt
loopcompletio
nstatemen
t
COIT29222 Structured Programming Slide 54
Activity
for ( int Counter = 0; Counter < 5; Counter++ ) {
cout << “Counter = “ << Counter << endl;}
What output is produced by the following code:
COIT29222 Structured Programming Slide 55
Activity Feedback
Counter = 0Counter = 1Counter = 2Counter = 3Counter = 4
The output produced by this code is:
COIT29222 Structured Programming Slide 56
Loop Control VariablesUsually an integer, but can be a character can be
declared within the for clause – instead of...int NbrLoops;cout << “Number of marks in exam ==> “; cin >> NbrMarks; cout >> “Number of students ==> “ cin >> NbrStudents; for (NbrLoops = 0; NbrLoops < NbrStudents; NbrLoops++){cout << “Student’s mark ==> “;cin >> StudentMark;Percentage = 100 * StudentMark / NbrMarks;cout << “ Student’s percentage: “;cout << Percentage;
}
COIT29222 Structured Programming Slide 57
cout << “Number of marks in exam ==> “; cin >> NbrMarks; cout >> “Number of students ==> “ cin >> NbrStudents; for (int NbrLoops = 0; NbrLoops < NbrStudents; NbrLoops++){
cout << “Student’s mark ==> “;cin >> StudentMark;Percentage = 100 * StudentMark / NbrMarks;cout << “ Student’s percentage: “;cout << Percentage;
}
Loop Control Variables
COIT29222 Structured Programming Slide 58
int NbrLoops;cout << “Number of marks in exam ==> “; cin >> NbrMarks; cout >> “Number of students ==> “ cin >> NbrStudents; for (int NbrLoops = 0; NbrLoops < NbrStudents; NbrLoops++){
cout << “Student’s mark ==> “;cin >> StudentMark;Percentage = 100 * StudentMark / NbrMarks;cout << “ Student’s percentage: “;cout << Percentage;
}
Loop Control Variables
notes: if you try to declare the same variable twice, you get a compilation error
COIT29222 Structured Programming Slide 59
Activity
for ( int Counter = 0; Counter != 5; Counter++ ) {
cout << “Counter = “ << Counter << endl; Counter = Counter + 1;}
What output is produced by the following code?
COIT29222 Structured Programming Slide 60
Activity Feedback
Counter = 0Counter = 2Counter = 4Counter = 6Counter = 8:( until you terminate the program! )
The output produced by this code is:
COIT29222 Structured Programming Slide 61
Activity
Write the for clause of a for loop to produce this output:
Counter = 15Counter = 14Counter = 13Counter = 12Counter = 11Counter = 10
COIT29222 Structured Programming Slide 62
Activity Feedback
The for clause of a for loop to produce this output is:
for ( int Counter = 15; Counter >= 10; Counter-- )
COIT29222 Structured Programming Slide 63
Nested LoopsWe saw that an if-else statement can be embedded
inside another if-else statement
Likewise, a for statement can be nested inside another for statement
In fact, any selection statement (if-else, switch) or repetition statement (while, do-while, for) can be embedded inside another selection or repetition statement
With a nested loop, one performs one or more trips around the inner loop for each trip around the outer loop.Here’s an example...
COIT29222 Structured Programming Slide 64
Nested Loops
for ( int RowNbr = 1; RowNbr <= 5; RowNbr++ ){ cout << endl << “Row “ << RowNbr << “:“; for ( int ColNbr = 1; ColNbr <= 3; ColNbr++ ) { cout << " Col " << ColNbr ; }}
inner loop
COIT29222 Structured Programming Slide 65
Activity
for ( int RowNbr = 1; RowNbr <= 5; RowNbr++ ){ cout << endl << “Row “ << RowNbr << “:“; for ( int ColNbr = 1; ColNbr <= 3; ColNbr++ ) { cout << " Col " << ColNbr ; }}
activity: what does this code produce as output
COIT29222 Structured Programming Slide 66
Activity Feedback
for ( int RowNbr = 1; RowNbr <= 5; RowNbr++ ){ cout << endl << “Row “ << RowNbr << “:“; for ( int ColNbr = 1; ColNbr <= 3; ColNbr++ ) { cout << " Col " << ColNbr ; }}
feedback: this code produces the following output… Col 1 Col 2 Col3
COIT29222 Structured Programming Slide 67
Nested Loops
for ( int RowNbr = 1; RowNbr <= 5; RowNbr++ ){ cout << endl << “Row “ << RowNbr << “:“; for ( int ColNbr = 1; ColNbr <= 3; ColNbr++ ) { cout << " Col " << ColNbr ; }}
outer loop
inner loop
COIT29222 Structured Programming Slide 68
Nested Loops
for ( int RowNbr = 1; RowNbr <= 5; RowNbr++ ){ cout << endl << “Row “ << RowNbr << “:“; for ( int ColNbr = 1; ColNbr <= 3; ColNbr++ ) { cout << " Col " << ColNbr ; }}
note: here, three trips around the inner loop are performed for each trip around the outer loop
COIT29222 Structured Programming Slide 69
Activity
for ( int RowNbr = 1; RowNbr <= 5; RowNbr++ ){ cout << endl << “Row “ << RowNbr << “:“; for ( int ColNbr = 1; ColNbr <= 3; ColNbr++ ) { cout << " Col " << ColNbr ; }}
activity: what is the output produced by this code?
COIT29222 Structured Programming Slide 70
Activity Feedback
for ( int RowNbr = 1; RowNbr <= 4; RowNbr++ ){ cout << endl << “Row “ << RowNbr << “:“; for ( int ColNbr = 1; ColNbr <= 3; ColNbr++ ) { cout << " Col " << ColNbr ; }}
feedback: the output produced by this code isRow 1: Col 1 Col 2 Col 3 Row 2: Col 1 Col 2 Col 3 Row 3: Col 1 Col 2 Col 3Row 4: Col 1 Col 2 Col 3
COIT29222 Structured Programming Slide 71
SummaryThe switch statements provide a convenient
alternative to simple if-else-if statements
The ternary operator provides some useful additional flexibility to the power of expressions
The task in the “do-while” loop is performed at least once
The for loop is useful when the number of required trips around a loop is known before entering the loop
Consequently, the for loop is useful when using arrays – the topic of a future class
top related