1 / 28

CSE 20232 Lecture 5 – Decisions and Loops

CSE 20232 Lecture 5 – Decisions and Loops. Switch Statement While… loop For… loop Do…While Loop Samples fstr sineplot switchit2. Switch Statement. Allows execution of one of several sequences of actions, depending on which constant matches the value of the expression

eunice
Download Presentation

CSE 20232 Lecture 5 – Decisions and Loops

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSE 20232Lecture 5 – Decisions and Loops • Switch Statement • While… loop • For… loop • Do…While Loop • Samples • fstr • sineplot • switchit2

  2. Switch Statement • Allows execution of one of several sequences of actions, depending on which constant matches the value of the expression switch ( <expression> ) { case <constant1> : <statements> // for <expression> == <constant1> break; case <constant2> : <statements> // for <expression> == <constant2> break; … default : <statements> // for <expression> != any <constant> }

  3. Switch Statement Example // Evaluate expression x op y (where op is +, -, * or /) int x, y; char op; cout << “enter any expression, such as 4 + 5: “; cin >> x >> op >> y; switch ( op ) { case ‘+’ : cout << “result = “ << x + y; // op == ‘+’ break; case ‘-’ : cout << “result = “ << x – y; // op == ‘-’ break; case ‘*’ : cout << “result = “ << x * y; // op == ‘*’ break; case ‘/’ : cout << “result = “ << x / y; // op == ‘/’ break; default : cout << “unknown operation “ // op != any known operation }

  4. if…else can do the same thing // Evaluate expression x op y (where op is +, -, * or /) int x, y; char op; cout << “enter any expression, such as 4 + 5: “; cin >> x >> op >> y; if ( op == ‘+’) cout << “result = “ << x + y; // op == ‘+’ else if (op == ‘-’) cout << “result = “ << x – y; // op == ‘-’ else if (op == ‘*’) cout << “result = “ << x * y; // op == ‘*’ else if (op == ‘/’) cout << “result = “ << x / y; // op == ‘/’ else cout << “unknown operation “ // op != any known operation

  5. Switch Statement • Warning • “break;” statements must be at the end of each sequence of statements • Otherwise, execution of statements continues into the next case • The “break;” forces execution to jump from there to the end of the switch statement

  6. Switch Statement w/o break; • The problematic switch below produces this output for input: 5 * 3 • result = 15result = 1unknown operation // Evaluate expression x op y (where op is +, -, * or /) int x, y; char op; cout << “enter any expression, such as 4 + 5: “; cin >> x >> op >> y; switch ( op ) { case ‘+’ : cout << “result = “ << x + y; // op == ‘+’ case ‘-’ : cout << “result = “ << x – y; // op == ‘-’ case ‘*’ : cout << “result = “ << x * y; // op == ‘*’ case ‘/’ : cout << “result = “ << x / y; // op == ‘/’ default : cout << “unknown operation “ // op != any known operation }

  7. A Use for a Switch Statement w/o some breaks // this switch works FINE // Evaluate expression x op y (where op is +, -, * or /) double x, y; char op; cout << “enter any expression, such as 4 + 5: “; cin >> x >> op >> y; switch ( op ) { case ‘-’ : y = -y; // negate y and then add it to x below case ‘+’ : cout << “result = “ << x + y; // op == ‘+’ or ‘-’ break; case ‘/’ : y = 1.0 / y; // invert y and multiply this inverse time x below case ‘*’ : cout << “result = “ << x * y; // op == ‘/’ or ‘*’ break; default : cout << “unknown operation “ // op != any known operation }

  8. While… Loop • Indefinite iteration • Allows repetition of a statement, as long as the expression is true while ( < expression> ) <statement>

  9. While… Loop Example • Program that prints table of squares and cubes #include <iostream> using namespace std; int main () { int n = 0; // intitalize n cout << “ Number Square Cube“ << endl; while (n <= 10) // test n against limit { cout << ‘\t’ << n << ‘\t’ << n*n << ‘\t’ << n*n*n << endl; n = n + 1; // increment n } return 0; }

  10. For… Loop • Definite Iteration (usually) • Allows repetition a predetermined number of times • Initializes loop counter(s) in the init section • Repeats statement as long as expression is true • Executes statements in the post section after each execution of the statement for ( <init>; <expression>; <post> ) <statement>

  11. For… Loop Example • Program that prints table of squares and cubes #include <iostream> using namespace std; int main () { cout << “ Number Square Cube“ << endl; // initilize n once, compare and postincrement each time for (int n = 0; n <= 10; n++) { cout << ‘\t’ << n << ‘\t’ << n*n << ‘\t’ << n*n*n << endl; } return 0; }

  12. Do…While Loop • Essentially and upside down while … loop • Executes the statement and then tests the expression to see if it continues to repeat do { <statement> } while ( <expression> );

  13. Do…While Loop Example • Program segment to ensure entering a value that makes sense int age; do { cout << “Please enter your age: “; cin >> age; if (age < 0) cout < “Age cannot be less than 0 years” << endl; } while (age < 0); cout << “Thanks, you are “ << age << “ year”; if (age > 1) cout << ‘s’; cout << “ old.” << endl;

  14. Implementing a Main Menu • Do • Output a list of user options • Read the user’s selection • Use switch statement to perform the correct selected action • While the user still wants to continue do { cout << ... cin >> selection; switch (selection) { ... } } while (selection != ‘q’);

  15. Quick Intro to Strings • The C++ Standard Library defines a string type • #include <string> • Strings can be assigned values, sent to cout, obtained from cin, concatenated together (+), etc. • Some examples: string name = “dan”; name = name + “ the man”; cout << “I am “ << name;

  16. Example 1 – fstr.cpp // File: fstr.cpp // Author: J H Stewman // Date: 3/5/2001 (modified 9/4/2003) // Purpose: // Things move faster in the world today. This program // reads text lines and removes vowels for fstr rdng. // Discussion: // Demo of the use of loops and the switch statement. #include <iostream> #include <string> #include <cctype> using namespace std;

  17. Example 1 – fstr.cpp int main () { char charIn; string sentenceOut; cout << "The world is a faster place these days!" << endl; cout << "Enter a short sentence and the extraneous characters" << " will be removed." << endl; cout << "-> "; sentenceOut = ""; // inititlizes it to empty string

  18. Example 1 – fstr.cpp // gets characters one at a time until newline is found while ((charIn = cin.get()) != '\n') { switch (toupper(charIn)) { case 'A': case 'E': case 'I': case 'O': case 'U': // there is really nothing to do but SKIP THIS VOWEL break; default: // concatenate this NON-VOWEL with the output string sentenceOut = sentenceOut + charIn; } }

  19. Example 1 – fstr.cpp cout << endl; cout << "Here is your sentence \"th fstr wy!\"" << endl << endl; cout << sentenceOut << endl << endl; return 0; }

  20. Fstr Sample Use The world is a faster place these days! Enter a short sentence and the extraneous characters will be removed. -> this is a test of the system. if this was a real emergency ... Here is your sentence "th fstr wy!" ths s tst f th systm. f ths ws rl mrgncy ...

  21. Example – switchit2.cpp // File: switchit2.cpp // Author: J H Stewman // Date: 3/2/2001 (modified 9/4/2003) // Purpose: Evaluation of binary expressions (integer arithmetic) // Discussion: // Illustrates use of the switch statement and the do-while // loop #include <iostream> using namespace std; int main ( ) { int left_operand, right_operand, result; char operation, response; bool error;

  22. Example – switchit2.cpp do { error = false; // get an input expression cout << "\nEnter a simple binary expression " << "(Ex: 3 + 5)" << endl; cout << "--> "; cin >> left_operand >> operation >> right_operand;

  23. Example – switchit2.cpp // perform specified operation (can only be one) switch (operation) { case '+': // addition result = left_operand + right_operand; break; case '-': // subtraction result = left_operand - right_operand; break; case'*': // multiplication result = left_operand * right_operand; break; case '/': // division result = left_operand / right_operand; break; case '%': //remainder result = left_operand % right_operand; break; default: // oops error = true; }

  24. Example – switchit2.cpp // show results to user if (!error) { cout << "(" << left_operand << " " << operation; cout << " " << right_operand << ") = " << result << endl; } else cout << "This is not a recognized binary expression." << endl; // find out whether to continue cout << "\nWould you like to enter another? (y/n)"; cin >> response; } while ((response == 'y') || (response == 'Y')); return 0; }

  25. Switchit2 Sample Use Enter a simple binary expression (Ex: 3 + 5) --> 3 + 5 (3 + 5) = 8 Would you like to enter another? (y/n)y Enter a simple binary expression (Ex: 3 + 5) --> 4 * 9 (4 * 9) = 36 Would you like to enter another? (y/n)y Enter a simple binary expression (Ex: 3 + 5) --> 23 - 5 (23 - 5) = 18 Would you like to enter another? (y/n)y Enter a simple binary expression (Ex: 3 + 5) --> 45 / 3 (45 / 3) = 15 Would you like to enter another? (y/n)n

  26. Example – SinePlot.cpp // File: sinePlot.cpp // Author: J H Stewman // Date: 9/7/2003 // Purpose: Demonstrate plot of sione function using loops // Discussion: // This program calculates the value of the sine function // over a range of 360 degrees and plots it (sideways) // on the screen #include <iostream> #include <iomanip> #include <cmath> using namespace std; int main ( ) { const double rads_per_degree = 2 * 3.14159 / 360.0; double thetaD, thetaR, sineTheta; int s; cout.setf(ios::fixed); // same as cout << fixed; // show header for table of values of theta & sin(theta) cout << "Theta(deg) | sin(theta)\n"; cout << "-----------------------\n";

  27. Example – SinePlot.cpp for (thetaD = 0; thetaD <= 360; thetaD += 10) { thetaR = thetaD * rads_per_degree; // convert to radians // output theta and sin(theta) for this display line cout << " " << setw(4) << setprecision(0) << thetaD; sineTheta = sin(thetaR); cout << " " << setw(7) << setprecision(4) << sineTheta; // compute integer position of function on display line s = 50 + (int)(25 * sineTheta); // draw function plot for this display line for (int x=25; x<=75; x++) { if (x == s) cout << "*"; // plot the function itself else if (x == 50) cout << "|"; // plot the 0-axis else if (((s < x) && (x < 50)) || ((50 < x) && (x < s))) cout << "-"; // show area between axis and function else cout << " "; // show blank spaces outside function } cout << endl; // go to next line on screen } return 0; }

  28. SinePlot Output Theta(deg) | sin(theta) ----------------------- 0 0.0000 * 10 0.1736 |---* 20 0.3420 |-------* 30 0.5000 |-----------* 40 0.6428 |---------------* 50 0.7660 |------------------* 60 0.8660 |--------------------* 70 0.9397 |----------------------* 80 0.9848 |-----------------------* 90 1.0000 |-----------------------* 100 0.9848 |-----------------------* 110 0.9397 |----------------------* 120 0.8660 |--------------------* 130 0.7660 |------------------* 140 0.6428 |---------------* 150 0.5000 |-----------* 160 0.3420 |-------* 170 0.1737 |---* 180 0.0000 * 190 -0.1736 *---| 200 -0.3420 *-------| 210 -0.5000 *-----------| 220 -0.6428 *---------------| 230 -0.7660 *------------------| 240 -0.8660 *--------------------| 250 -0.9397 *----------------------| 260 -0.9848 *-----------------------| 270 -1.0000 *-----------------------| 280 -0.9848 *-----------------------| 290 -0.9397 *----------------------| 300 -0.8660 *--------------------| 310 -0.7660 *------------------| 320 -0.6428 *---------------| 330 -0.5000 *-----------| 340 -0.3420 *-------| 350 -0.1737 *---| 360 -0.0000 *

More Related