710 likes | 807 Views
COIT29222-Structured Programming Lecture Week 06. Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters 4 & 5 This week, we will cover the following topics: More on Selection -switch statement -selection (ternary) operators
E N D
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
Selection statements • We 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 statement • ternary operators
if-else – a review • Let’s start out by reviewing what we know about the if-else statement. if statement if (Age < 18) { cout<<“A child!“<<endl; } if-else statement if (Age < 18) { cout<<“A child!“<<endl; } else { cout<<“An adult!“<<endl; }
if-else-if statement if (Age < 13) { cout<<“A child!“<<endl; } else if ((Age >= 13 ) && (Age <= 17)) { cout<<“A teenager!“<<endl; } else { cout<<“An adult!“<<endl; }
Braces • if (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.
Nested if/else if (Gender==‘M’) if (Age < 18) cout<<“Amale child!“<<endl; else cout<<“A man!“<<endl; else if (Age < 18) cout<<“Afemale child!“<<endl; else cout<<“A woman!“<<endl;
Nested if/else if (Gender==‘M’) if (Age < 18) cout<<“Amale child!“<<endl; else cout<<“A man!“<<endl; else if (Gender==‘F’) if (Age < 18) cout<<“Afemale child!“<<endl; else cout<<“A woman!“<<endl; else cout<<“Unknown gender!“<<endl;
Other selection statements • Selection 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...
Other selection statements Data 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...
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!"; } functions Or, we can use a switch statement...
notes: a little easier to read than if-else-if 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 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 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!"; } }
The switch statement • switch 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> ) {...}
The switch statement or, 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
The switch statement or, 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
The switch statement or, 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
The switch statement or, 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
Optional break;? switch ( CharMenuSelection ) { case 'a': case 'A': ProcessSelectionA; break; case 'b': case 'B': ProcessSelectionB; break; : }
Ternary operator • C++ 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...
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"; ifcondition is True, expression 1 is evaluated; otherwise, expression 2 is evaluated
More on Loops • We 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; }
while – a Review • Commonlooping 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…
while – a Review • < initialise variables in while-condition > • while ( <condition> ) • { • < while statements > • < updatevariables in while-condition > • } • NbrTimesTold = 0; • while (NbrTimesTold < NbrTimesToTell) • { cout << “No new taxes!“ << endl; NbrTimesTold = NbrTimesTold + 1; }
Activity • What will the following code output? Number = 5; while (Number > 0) { Sum = Sum + Number ; Number = Number - 1 ; } cout <<“The sum is “<<Sum <<endl;
Activity Feedback • Output depends on initial value of Sum • if Sum is zero at start: “The sum is 15” • must always initialise a sum to zero! Number = 5; while (Number > 0) { Sum = Sum + Number ; Number = Number - 1 ; } cout <<“The sum is “<<Sum <<endl;
Activity • What will the following code output? Sum = 0 ; while (Number > 0) { Sum = Sum + Number ; Number = Number - 1; } cout <<“The sum is “<<Sum <<endl;
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;
Activity • What will the following code output? Sum = 0 ; Number = 5; while (Number > 0) { Sum = Sum + Number ; Number++; } cout <<“The sum is “<<Sum <<endl;
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;
while vs do-while • The while statement tests a condition atthe start of the loop • The do-while statement tests a condition atthe endof the loop
while vs do-while • The while statement tests a condition atthe startof 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; }
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-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’));
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?
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; }
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’));
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’));
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; }
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 );
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.
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
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: initialiseloop control variable
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
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)
for vs while 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; } notes: initialiseloop control variable
for vs while 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; } notes: loop condition
for vs while 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; } notes: modify loop control variable (to avoid looping forever)
for Loop Syntax for( < loop initialisation statement > ; < loop condition > ; < loop completion statement > ) { < for statements > } notes: parentheses around forclause
for Loop Syntax for( < loop initialisation statement > ; < loop condition > ; < loop completion statement > ) { < for statements > } notes: statement performed once before entering loop for first time
for Loop Syntax for( < loop initialisation statement > ; < loop condition > ; < loop completion statement > ) { < for statements > } notes: semi-colons after loop initialisation and loop condition