Download
further control structures n.
Skip this Video
Loading SlideShow in 5 Seconds..
Further Control Structures PowerPoint Presentation
Download Presentation
Further Control Structures

Further Control Structures

97 Views Download Presentation
Download Presentation

Further Control Structures

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Further Control Structures • I will go over some important topics today. • Loops and conditionals are essential for ones development in any programming language. • We will look at the three types of looping mechanisms • for • do-while • while • We will also look again at the if statement only if it is required.

  2. Week 4 Topics • Switch Statement for Multi-way Branching • Can be achieved with an if statement • This was previously looked at • We have to be careful with the “fall through” mechanism however. • Do-While Statement for Looping • For Statement for Looping • Using break and continue statements • These are used predominantly with the switch statement

  3. Display a menu Simple Menus • Program displays a menu of choices • User enters a choice • Program responds to choice • Go back to to 1

  4. Display a menuSimple DisplayMenu() function #include <iostream> void DisplayMenu(void); int main( ) { return 0; } function prototype consisting of <type> function name (types of parameters); So void here means no return type or parameters expected. It is not required to use void here.

  5. Display a menuSimple DisplayMenu() function #include <iostream> void DisplayMenu(void); int main() { return 0; } void DisplayMenu(void) { cout << “*********** MENU **************\n”; cout <<endl; cout << “ 1. Man United” << endl; cout << “ 2. Chelsea” << endl; cout << “ 3. Arsenal” << endl; cout << “ 4. Quit” << endl; cout << endl; cout << “Please choose 1, 2, 3 or 4 : “; } Definition: like a mini program or sub program

  6. Display a menuSimple DisplayMenu() function #include <iostream> void DisplayMenu(void); int main() { int response; DisplayMenu(); return 0; } void DisplayMenu(void) { cout << “*********** MENU **************\n”; cout <<endl; cout << “ 1. Man United” << endl; cout << “ 2. Chelsea” << endl; cout << “ 3. Arsenal” << endl; cout << “ 4. Quit” << endl; cout << endl; cout << “Please choose 1, 2, 3 or 4 : “; } Function call from within main() Prompt

  7. User enters choice • Prompt was part of function DisplayMenu • use cin to get a response from user. • The function is invoked by a call from another function, in this case the calling function is main() • The call is just a writing of the function name in this case, with no parameters passed to this function

  8. Display a menu and Get response #include <iostream> void DisplayMenu(void); int main() { int response; DisplayMenu(); cin >> response; return 0; } void DisplayMenu(void) { cout << “*********** MENU **************\n”; cout <<endl; cout << “ 1. Man United” << endl; cout << “ 2. Chelsea” << endl; cout << “ 3. Arsenal” << endl; cout << “4. Quit” << endl; cout << endl; cout << “Please choose 1, 2 or 3 : “; } Get response

  9. Process the response by using the switch statement

  10. What isthe switch Statement • Similar to the if statement • Can list any number of branches • Used in place of nested if statements • Used only with integer expressions (true/false or int or char) • Avoids confusion of deeply nested if statements

  11. The switch Statement Syntax switch (expression) { case value1: statement1; break; case value2: statement2; break; case valueN: statementN; break; default: statement;} expression must return an integer value, i.e. be an integer

  12. The switch Statementwith char expression switch (choice) { case 1: cout << “The greatest ” << endl; break; case 2: cout << “Exciting team ”<< endl; break case 3: cout << “Boring ” << endl; break; case 4: cout << “Bye Bye” << endl; } //next statement

  13. What is the purpose of the break statement?The break Statement prevents “fall through”it makes the computer jump out of the current block, recall that the switch statement will execute all statements below the point of entering the statement. This can be a problem.

  14. The switch Statement illustrate fall through again switch (choice){ case 1: cout << “The greatest ” << endl; case 2: cout << “Exciting team ”<< endl; case 3: cout << “Boring ” << endl; case 4: cout << “Bye Bye << endl; }

  15. The switch Statement What will be the output when the user enters 1? The greatest Exciting team Boring Bye Bye

  16. The switch Statement What will be the output when the user enters 2? Exciting team Boring Bye Bye

  17. The switch Statement What will be the output when the user enters 3? Boring Bye Bye

  18. The switch Statement What will be the output when the user enters 4? Bye Bye

  19. Classic use of switch Statements: for Menu processing * * * * Menu * * * * 1. Man United 2. Chelsea 3. Arsenal 4. Quit Choose either 1, 2, 3 or 4:

  20. Example program to Demo #include <iostream> //see displaymenu3.cpp Using namespace std; void DisplayMenu(void); int main(void) { int choice; DisplayMenu(); cin >> choice; switch (choice) { case 1: cout << “The greatest“ << endl; case 2: cout << “Exciting team“ << endl; case 3: cout << “Boring“ << endl; case 4: cout << “Bye Bye << endl; }; return 0; } void DisplayMenu(void) { cout << "*********** MENU **************\n"; cout <<endl; cout << " 1. Man United" << endl; cout << " 2. Chelsea" << endl; cout << " 3. Arsenal" << endl; cout << endl; cout << "Please choose 1, 2 or 3 : "; }

  21. The switch Default Statement captures errors or perform default actione.g. if user enter any other number switch (choice){ case 1: cout << “The greatest ” << endl; break; case 2: cout << “Exciting team ”<< endl; break; case 3: cout << “Boring ” << endl; break; case 4: cout << “Bye Bye “ << endl; break; default: “Incorrect choice” << endl; }

  22. Nested Switch Statements For example: switch( CarType ) { case MONDEO:   switch( EngineCapacity)    {    case 1500:cout << “This is underpowered “; break;    case 1800: cout << “This is just right”;        break;    case 2000: cout<<“This is expensive to run”; }; //closes second switch case FIESTA:  break; default:    cout << “Unknown model”; } //closes first switch

  23. Problems with switch • Strange rules, once a condition is tested true execution proceeds until break or end of switch. • Control “falls through” the switch • Get in the habit of always putting breaks in and putting a default condition in. • Less satisfactory to use where floats or Boolean expressions are tested. • Putting in semi colon ‘;’after case rather than colon ‘:’

  24. Recall Purpose of Loops/Repetition • To apply the same steps again and again to a block of statements. • Recall a block of statement is one or more statement, block usually defined by braces { … } with syntactically correct statements inside.

  25. Most Common Uses of LoopsYou should master all these! • For counting • For accumulating, i.e. summing • For searching • For sorting • For displaying tables • For data entry – from files and users • For menu processing • For list processing

  26. Types of loops while for do..while

  27. C/C++ Loop Structures • Pre-test (the test is made before entering the loop) • while loops • general purpose • Event controlled (variable condition) • for loops • When you know how many times (fixed condition) • When you process arrays (more in later lectures) • Post-test (the test is done at the end of the loop) • do … whileloops • When you do not know how many times, but you know you need at least one pass. • Data entry from users

  28. Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while (Expression) ; //note semi colon Loop body statement can be a single statement or a block.

  29. Function Using Do-While void GetYesOrNo ( char response ) //see UseofFunction1.cpp // Inputs a character from the user // Postcondition: response has been input // && response == ‘y’ or ‘n’ { do { cin >> response ; // skips leading whitespace if ( ( response != ‘y’ ) && ( response != ‘n’ ) ) cout << “Please type y or n : “ ; } while ( ( response != ‘y’ ) && ( response != ‘n’ ) ) ; } 29

  30. POST-TEST loop (exit-condition) The looping condition is tested after executing the loop body. Loop body is always executed at least once. PRE-TEST loop (entry-condition) The looping condition is tested before executing the loop body. Loop body may not be executed at all. Do-While Loopvs. While Loop

  31. Do-While Loop DO When the expression is tested and found to be false, the loop is exited and control passes to the statement that follows the do-while statement. Statement WHILE Expression TRUE FALSE

  32. The for Statement Syntax while condition change expression start condition Example: for (count=1; count < 7; count++) { cout << count << endl; } //next C++ statements;

  33. The for Statement • Used as a counting loop • Used when we can work out in advance the number of iterations, i.e. the number of times that we want to loop around. • Semicolons separate the items in the for loop block • There is no semi colon at the end of the for loop definition at the beginning of the statement

  34. A Simple ExampleCreate a table with a for loop int num;cout<< "NUMBER\tSQUARE\tCUBE\n“; cout << "------\t------\t----\n"; for (num = 1; num < 11; num++) { cout << num << “\t“; cout << num * num<< “\t“; cout << num * num *num<<“\n";}//see useofFunction2.cpp NUMBER SQUARE CUBE ---------- ---------- ------ 1 1 1 2 4 8 . . . . . . 10 100 1000

  35. Use of the for loop • Please see the following files • Harmonic.cpp • BaselSeries.cpp These are two very important series in mathematics.

  36. for and if Statements working together. • Simple search for divisors • Given an integer number find all the numbers that divide exactly into it (including 1 and itself). • e.g. if number = 12, divisors are 1,2,3,4,6,12 Think I can use % operator to find divisors

  37. Solution Design • Get the number from user • By starting with check number=1 and finish with number (is this efficient?) • find the remainder of dividing number with current check number • if remainder is 0 display current check number as a divisor. • otherwise do not display anything

  38. Program fragment for finding divisors of an integer cout << “Enter an integer :”; cin >> number; for (j = 1; j <= number; j++) { if (number % j == 0) { cout << j << “ is a divisor of “; cout << number << endl; } }//see useofFunction3.cpp, this program determines whether we have a perfect number

  39. Common errors in constructing for Statements for (j = 0, j < n, j = j + 3) // commas used when semicolons needed for (j = 0; j < n) // three parts needed for (j = 0; j >= 0; j++) ?????what is wrong here ????? for (j=0, j=10; j++);

  40. Infinite loops example 1 for (j=0; j>=0; j++) { cout << j << endl; } What will happen here? //see infiniteloop1.cpp

  41. Loop design Seven Loop Design Factors • What is the condition that ends the loop? • How should the condition be setup or primed? • How should the condition be updated? • What processes are being repeated? • How do you set up the processes? e.g. initialise event counters or accumulators • How is the process updated? e.g. update accumulators and counters • What is the expected state of the program at exit from loop?

  42. Programming convention • Use of integers called i,j,k • You will see them all the time. • Most commonly used as loop control variables • Conventionally used for counters • We will see later that counters often have a dual use as array indices. • arrays to be discussed in later lectures • When you see i,j,k declared expect to see a loop!

  43. Example of Repetition int n; for ( int i = 1 ; i <= n; i++) { cout << i << “ Potato” << endl; } //see usefor1.cpp // useofFunction5.cpp uses an array as a global variable

  44. Example of Repetition ? num int n; for ( int i = 1 ; i <= n; i++) cout << i << “ Potato” << endl; OUTPUT

  45. Example of Repetition 1 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT

  46. Example of Repetition 1 num true int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT

  47. 1Potato Example of Repetition 1 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT

  48. 1Potato Example of Repetition 2 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT

  49. 1Potato Example of Repetition 2 num true int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT

  50. 1Potato 2Potato Example of Repetition 2 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT