1.11k likes | 1.13k Views
Learn about loops, conditionals, and switch statements for efficient program control. Code examples and explanations provided.
E N D
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.
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 “fall through” however • Do-While Statement for Looping • For Statement for Looping • Using break and continue statements • This is used predominantly with the switch statement
Display a menu Simple Menus • Program displays a menu of choices • User enters a choice • Program responds to choice • Go back to to 1
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.
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
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
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
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
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
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
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
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.
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; }
The switch Statement What will be the output when the user enters 1? The greatest Exciting team Boring Bye Bye
The switch Statement What will be the output when the user enters 2? Exciting team Boring Bye Bye
The switch Statement What will be the output when the user enters 3? Boring Bye Bye
The switch Statement What will be the output when the user enters 4? Bye Bye
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:
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 : "; }
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; }
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”; }; case FIESTA: break; default: cout << “Unknown model”; }
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 ‘:’
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.
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
Types of loops while for do..while
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
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.
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
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
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
The for Statement Syntax while condition change expression start condition Example: for (count=1; count < 7; count++) { cout << count << endl; } //next C++ statements;
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
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
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
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
Program fragment for finding divisors of an integer cout << “Enter an integer :”; cin >> number; for (j = 1; j <= number; j = j + 1) { if (number % j == 0) { cout << j << “ is a divisor of “; cout << number << endl; } }//see useofFunction3.cpp
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++);
Infinite loops example 1 for (j=0; j>=0; j++) { cout << j << endl; } What will happen here //see infiniteloop1.cpp
Loop design 7 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?
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!
Example of Repetition int n; for ( int i = 1 ; i <= n; i++) { cout << i << “ Potato” << endl; } //see usefor1.cpp // useofFunction5.cpp
Example of Repetition ? num int n; for ( int i = 1 ; i <= n; i++) cout << i << “ Potato” << endl; OUTPUT
Example of Repetition 1 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
Example of Repetition 1 num true int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato Example of Repetition 1 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato Example of Repetition 2 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato Example of Repetition 2 num true int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato 2Potato Example of Repetition 2 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato 2Potato Example of Repetition 3 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT