530 likes | 722 Views
Before going into Chapter 4 Let ’ s look at ways to format output discussed in Chapter 3 of your text. Output of a program RUN should be well-defined. Tell the user clearly what the output means Give unit of measures Output of a program RUN should be pleasing to the eye and easy to read.
E N D
Before going into Chapter 4 Let’s look at ways to format output discussed in Chapter 3 of your text. • Output of a program RUN should be well-defined. • Tell the user clearly what the output means • Give unit of measures • Output of a program RUN should be pleasing to the eye and easy to read. • Be careful with spaces. • Make columns when useful. • Use functions from #include <iomanip> for some numbers. • Always show a title for your output in the .dat file. • Use the “\n\n\t “ liberally to make the title stand out. • Make a real effort to have output that is pleasing to the eye and easy to read.
Formatting Output & HOMEWORK • We can format output with the use of endl; andthe escape characters listed on p. 61 of your text such as \n, \t, \v, etc. • Sometimes we want to format the display of numbers with special manipulator functions found in the iomanip library. • Need the preprocessor command: #include <iomanip> • setw(n): • Sets the width of field for a number. • Used to right justify numbers. • The value in n must be large enough to accommodate all the digits and decimal point. Otherwise setw(n) will be ignored. Homework: Try these and discuss:
Formatting Output & HOMEWORK • We can format output with the use of endl; andthe escape characters listed on p. 61 of your text such as \n, \t, \v, etc. • Sometimes we want to format the display of numbers with special manipulator functions found in the iomanip library. • Need the preprocessor command: #include <iomanip> • fixed or you can use setiosflags (ios:: fixed): • Forces the display of a decimal point and six digits after the decimal point. • Usually used with setprecision(n). • setprecision(n): • n determines how many digits to display after the decimal point. • Rounds the decimal portion when necessary. • setprecision(2) is used for dollars and cents money values. Why? More HOMEWORK: Try these and discuss: cout << “|” << setw(8) << setiosflags (ios:: fixed) << setprecision(3) << 132.9 <<“|\n”; cout << “|” << setw(7) << setiosflags (ios:: fixed) << setprecision(2) << 2.916 <<“|\n”; cout << “|” << setw(6) <<setiosflags (ios:: fixed)<< setprecision(2) << 3.4 <<“|\n”;
Formatting Output & HOMEWORK • We can format output with the use of endl; andthe escape characters listed on p. 61 of your text such as \n, \t, \v, etc. • Sometimes we want to format the display of numbers with special manipulator functions found in the iomanip library. • Remember the preprocessor command: #include <iomanip> • The manipulators setw(n), fixed, and setprecision(n) are the most commonly used, but there are more. See pp. 119-130 in your text. • More HOMEWORK: Do exercises 6 and 7 on p.130.
Chapter 4 Selection Structuresifstatementsif/else statementsNested if or if/else within if and/or else statements
Single alternative decision or one-way selection. Double alternative decision Or two-way selection. Branching the Control of Flow of Program Execution Using: if (something is true) Do something or continue with program --------------------------------------------------------------- if ( something is true) { do something; } else { do something different; } Or switch and case statements to be discussed later.
Series of if Statements Examine and discuss code. if (cents >= 10) { dimes = cents/10; cout << "\n dimes "<< dimes; writefile << "\n dimes "<< dimes; cents %= 10; } if (cents >= 5) { nickels = cents/5; cout << "\n nickels "<< nickels; writefile << "\n nickels "<< nickels; cents %= 5; } if (cents >= 1) { cout << "\n pennies "<< cents; writefile<< "\n pennies "<< cents; } cout << "\n \n\n"; } Making Change void getCents(int ¢s, ofstream &writefile) { cout << "Select a number of cents. "; cin >> cents; writefile<<“\n\n\tMaking Change\n”; writefile << “The number of cents: “ << cents << endl; } void change(int cents, ofstream &writefile) { int quarters, dimes, nickels; if (cents >= 25) { quarters = cents/25; cout << "\n quarters "<< quarters ; writefile<< "\n quarters "<< quarters ; cents %= 25; } Should there be a check for bad input. Why and where?
Selection using if/else statement Two-way Selection 4b Nice Name void getName(string &name, , ofstream &writefile) { cout << "enter name: "; cin >> name; writefile<<“\n\n\tNice Name\n”; writefile<<“The name is: “ << name << endl; } void response(string name, ofstream &writefile) { if (name ==“Joe") { cout << ” That’s a very nice name" << endl; writefile << ” That’s a very nice name" << endl; } else { cout << name << " might be a nice name" << endl; writefile << name << " might be a nice name" << endl; } } • What if user enters “joe” ? or “ Joe” We want programs to be robust so try: if (name == “Joe” || name == “joe”)
Relational Operators < > == != <= >= ex: a > b Is aisgreater thanb Relational Operators and Logical OperatorsUsed in if statements • Logical Operators • ! not • && and • || or • ex: • a && b • True if aandb are true • a || b • True if only aor only b are • true or if both are true
Logical operators • Boolean expressions can be combined using logical operators: AND, OR, NOT • C++ equivalents are &&, ||, and !, respectively • What range of values generates ‘A’ message? Problems? if (90<= grade && grade < 95) { cout << "that’s an A" << endl; } && Both sides must be true AND || Only one side needs to be true. OR ! Take opposite: true becomes false; false become true
The following expression was intended to determine whether num is between low and high (inclusively). Unfortunately, it doesn't work this way in C++. If (low <= num <= high) Write a corresponding expression that does work
The following expression was intended to determine whether num is between low and high (inclusively). Unfortunately, it doesn't work this way in C++. If (low <= num <= high) Write a corresponding expression that does work. If (low <= num && num <= high) Each inequality has to be written separately and joined by &&.
Nested if and/or else statements Discuss all combinations of these statements. if ( something is true) { if (something different is true) { do something } else { do something different } } else { if (another thing is true) { do something else; } }
void getInts(int &a, int &b, int &c, ofstream &writefile) { cout << "Enter 3 integers with a space between. ”; cin >> a >> b >> c; writefile <<“\n\n\t Finding The Minimum Number\n”; writefile << “The three integers are: “<< a <<“ “ << b << “ “ << c << end; } void displayMinimum(int a, int b, int c, ofstream &writefile) //Program 4c { int minimum; if (a < b) { if (a < c) { minimum = a; } else { minimum = c } } else { if (b < c) { minimum = b; } else { minimum = c; } } cout << "\n \n\n The smallest number is " << minimum << "\n\n\n”; writefile<< "\n \n\n The smallest number is " << minimum << "\n\n\n”; } There is a more elegant solution to this problem, but this is a nice demo of nested if/else statements. Please note the even number of { } open and close braces. Always check that there is a close brace for every open brace. Examine and discuss each line of code.
A Few Important Points and Some Exercises More On Relational Operators • The guard test in an if statement must be a Boolean expression (named for George Boole) • Values are true and false int degrees; boolisHot = false; // bool is a built-in type like int, double. cout << “Enter temperature: "; cin >> degrees; if (degrees > 95) { isHot = true; } // more code here // What is the output for : cout << isHot; • Relational operators are used in expressions to compare values: • <, <=, >, >=, ==, !=are used with many types and always evaluate to true or false.
Details of Relational Operators • Relational (comparison) operators work as expected with int and double values, what about string and bool? 23 < 45 49.0 >= 7*7 "apple" < "berry" • Strings are compared alphabetically so that "ant" < "zebra" but (suprisingly?) "Ant" < "zebra“. Why? • Which it true? ant < Zebra or Zebra < ant • Boolean values have numeric equivalents, 1 is true, 0 is false • Any non-zero number is read as true (1) and zero is read as false (0) cout << (23 < 45) << endl; cout << ("guava" == "Guava") << endl;
Relational Operators: details… • Use parentheses liberally, or hard-to-find problems occur • if (4 + 7 * 6/ 10 – 4 < 2 * 8 – 3 * 4) • Separate the two sides of the relational operator first. • if ((4 + 7 * 6/10 - 4)<(2 * 8 – 3 * 4)) • How many term are in the numerator and how many in the denominator? Is it the above or (((4+7*6)/(10-4))<(2*8 – 3*4)) or some combination of this? • What is being subtracted on the right side of the relational operator? Is it 16 - 12 = 4 or 2 * (8 - 3) * 4 = 40 ? • What about true/false and numeric one/zero equivalent? if (3 + 4 – 7) //what does this mean? { cout << "hi" << endl; } else { cout << "goodbye" << endl; }
Short-circuit Evaluation With Logical Operators • Subexpressions in Boolean expressions are not evaluated if the entire expression’s value is already known if ((count != 0) && (scores/count) < 60) { cout << "low average warning" << endl; } • Potential problems if there are no grades to average? • What happens in this case? Short circuit evaluation Fill in the blanks for && and then for ||: • If the first subexpression or left hand side is _______, do not evaluate the next one because the whole experssion is ______.
Numerical Accuracy Problem • Sometimes == does not evaluate to true when it should evaluate to true. • This is true for double and float numbers. double a, b if (a ==b) { //do something } • When ( a==b) does not evaluate to true and you know it should, then do the following in your if statement. If (abs(a-b) < 0.000001) { //do something } • See p.183 in your text
Let’s review what we have learned with some exercises. What is output by the following (somewhat tricky) code segment? int x; cout << (x = 7) << endl; HOMEWORK Write an if/else statement which outputs the word "yes" if variables x and y have the same value, otherwise it outputs the word "no".
HOMEWORK What is output by the following (somewhat tricky) code segment? Justify your answer in one or two sentences. intnum = 5; int prod = 8; if (prod = num) { cout << "equal" << endl; } else { cout << "different" << endl; }
HOMEWORK The following code segment causes a compiler error. Why? How can the error be fixed? string language = “C++”; if (language == "C++") cout << "Welcome to the world of C++" << endl; cout << " the industry standard!" << endl; else cout << "Oh well, programming is programming." << endl;
HOMEWORK Write a code segment which reads in two strings, and outputs the word "different" if the input values are different.
HOMEWORK What is output by the following (somewhat tricky) code segment? int foo = -1; if (foo < 0) { cout << "negative" << endl; foo = -foo; //Pay attention to this line. } if (foo == 0) { cout << "zero" << endl; } if (foo > 0) { cout << "positive" << endl; }
HOMEWORK TRUE or FALSE? The following statement prints a "proper" message identifying whether the value of num is even. if (num % 2 == 0) { cout << "number is even" << endl; } else { cout << "number is odd" << endl; }
HOMEWORK What is output by the following code segment? int x = 1, y = 0; if (x >= y && x != 0) { cout << "foo" << endl; } else { cout << "bar" << endl; } If x = 3, y = 7, and z = 10, which of the following boolean expressions evaluate to true? ·(x <= y && y <= z) ·!((x+y) == z) ·(x != y || y > z) ·!(x > z && y > z) ·(x == y || (x != z && y == z))
else if ladder Multiple Alternatives Your text calls it else if chain Multiple Selections if (first condition is true) { Do first option } else if (second condition is true) { Do second option } else if (third condition is true) { Do third option } else { Do this when all the above are false. }
Write a code segment which reads in an integer (call it num) and outputs the word "positive" if num is greater than zero, "zero" if num is equal to zero, or "negative" if num is less than zero. intnum; cout << "Enter an integer: "; cin >> num; if (num > 0) { cout << "positive" << endl; } else if (num == 0) { cout << "zero" << endl; } else { cout << "negative" << endl; } Why is a check for bad input not necessary here ?
Note: There should be a check for bad input here and on the next slide.Use a do/while loop. Discuss where and how for each. 4d void getGrade(double &grade, ofstream &writefile) { cout << "Enter a test grade between 0 and 100 "; cin >> grade; writefile << “\tConvert Number Grade to Letter Grade.\n\n”; writefile << “The number grade is: “ << grade << endl < <endl; } void Lettergrade(double grade, ofstream &writefile) if (grade>= 90 && grade <= 100) { cout << " your grade is an \'A\'\n"; writefile << " your grade is an \'A\'\n”; } else if (grade >= 80 && grade <90) { cout << " your grade is an \’B\'\n"; writefile << " your grade is an \’B\'\n”; } else if (grade >= 70 && grade <80) { cout << " your grade is a \'C\'\n";writefile << " your grade is a \'C\'\n”; } else if (grade >= 60 && grade <= 70) { cout << " your grade is a \'D\'\n"; writefile << " your grade is a \'D\'\n”; } else { cout << " your grade is an \'F\'\n";writefile<< " your grade is an \'F\'\n”; } Compare the series of if statements on next slide with this else if ladder. Why use each structure ?
Series of if Statements Examine and discuss code. if (cents >= 10) { dimes = cents/10; cout << "\n dimes "<< dimes; writefile << "\n dimes "<< dimes; cents %= 10; } if (cents >= 5) { nickels = cents/5; cout << "\n nickels "<< nickels; writefile << "\n nickels "<< nickels; cents %= 5; } if (cents >= 1) { cout << "\n pennies "<< cents; writefile<< "\n pennies "<< cents; } cout << "\n \n\n"; } 4a: Making Change void getCents(int ¢s, ofstream &writefile) { cout << "Select a number of cents. "; cin >> cents; writefile<<“\n\n\tMaking Change\n”; writefile << “The number of cents: “ << cents << endl; } void change(int cents, ofstream &writefile) { int quarters, dimes, nickels; if (cents >= 25) { quarters = cents/25; cout << "\n quarters "<< quarters ; writefile<< "\n quarters "<< quarters ; cents %= 25; }
Homework Write a two code segments which has a check for bad input in the previous two slides.
switch and case statements Another structure for multiple alternatives Switch may only have an expression that evaluates as an integer (int, char, or bool) to be compared with specific values in the cases. switch (expression) { case value1: statement1; statement2; break; case value2: statement3; statement4; break; case value3: statement5; statement6; break; Default: Do when no case is selected }
switch Syntax for switch statements. Curly braces for the switch statement, but no curly braces for the case statements. case statements and default statements followed by colon. break causes the program to jump out of the switch. Otherwise there would be a fall through to the next case. cout<<“Input 1 or 2”; cin>>rnum; switch (rnum) { case 1: cout << “one” << endl; break; case 2 : cout << “two” << endl; break; default: cout <<“oops !” ; break; } /* The default is often a check for bad input. This makes the program robust. */
MORE ON SWITCH { case 1: case 2: cout << “small”; break; case 8: case 9: cout<<“big”; break; default: cout <<“oops !” break; }
MORE ON SWITCH Switch (daynumber) { case 1: cout << “weekend day”; break; case 2: case 3: case 4: case 5: case 6: cout << “weekday”; break; case 7: cout<<“weekend day”; break; default: cout <<“You did not enter a number for the day!” break; }
Switch statements are often used with a menu of choices. void getInts(int &fnum, int &snum, ofstream &writefile)//Problem 4e { cout << “Please type in two numbers with a space between: “; cin >> fnum >>snum; writefile >>”\n\n \t Mathematical Operations On Two Numbers\n”; writefile >>”The two numbers are” << fnum << “ and “ << snum << endl << endl; } ********NOTE to students:****************************************************************** void menu(int &opChoice) { cout<< “What would you like to do with these numbers?\n\n”; cout << “ 1. addition /n”; cout << “ 2. multiplication /n”; cout << “ 3. division /n”; //Because of the division snum cannot be zero. //This requires a check for bad input. cin >> opChoice; writefile <<“ “//students enter menu list here.writefile<<“The choice is “ << 0pChoice << endl <<endl; }
Switch statements are often used with a menu of choices. void operation(intfnum, intsnum, intopChoice, ofstream &writefile ) { switch (opChoice) { case 1: cout << “the sum of the numbers is “<< fnum + snum <<endl; writefile << “the sum of the numbers is “<< fnum + snum <<endl; break; case 2: cout << “the product of the numbers is “<< fnum * snum <<endl; writefile<< “the product of the numbers is “<< fnum * snum <<endl; break; case 3: cout << “the first number divided by the second is “<< fnum / snum <<endl; writefile << “the first number divided by the second is “<< fnum / snum <<endl; break; default: cout << “You did not select one of the choices so no operation is performed.\n”; writefile << “You did not select one of the choices so no operation is performed.\n”; } }
Homework • There has to be a check for bad input when division is involved. Why? • There are two possible places where a check for bad input could be placed in the code of the previous two slides. If you were writing the program, you would chose only one. For the homework exercise, though, do the following: • Write a code segment showing a check for bad input on the first slide . • Write a code segment showing a check for bad input only for division on the second slide.
Theif Statement and the whileStatement • They have the same structure, however: • The body of an if statement is executed once when the if condition evaluates as true. • The body of the while statement can be executed over and over as long as the while condition evaluates as true. • Something inside the while loop must change the condition so that the while statement eventually evaluates as false. The if Statement and the while Statement
true true test test false false Statement list Next statement Statement list Next statement Semantics of while loop if (test) while (test) { { statements; statements; statements; statements; } }
From Selection to Repetition • The if statement and if/else statement allow a block of statements to be executed based on a condition. if (area > 20.0) { cout << area << "is large" << endl; } • The while statement repeatedly executes a block of statements while the condition is true. intmain() **Note:The whole while loop and inta, b, c; call statements hsve to be string answer; between the if file fail() boolisRerunning = true statements and the close() while (isRerunning == true)statement. The fail(), open(), { and close()statements are not getInfo(a, b, c); shown here. displayBiggest(a, b, c); cout<<“\nWould you like to run this program again? y/n”; cin >> answer; if(answer == “n”) { isRerunning = false; } } return 0; }
Model 4 Program • Load your template. Change the date. • Modify it to the following: • /* Specs: (what program does) • 1. lab/program #/name: Determine volumes of five different solid shapes. • 2. Desired output: The volume of different shapes. • 3. Given input: Choice of shape, radius, length, width, height. • 4. Process: if, else/if ladders, case/switch, for loop, while loop, do/while loop. • Equations: Sphere = (4/3)*PI*pow(radius, 3), Cube=pow(length, 3), Rectangular Prism=length*width*height , Cone=(1/3)*PI*pow(radius, 2)*height, Cylinder=PI*pow(radius, 2)*height • */ • include <iostream> • #include <cstring> • #include <cmath> • #include <fstream> • #include <cstdlib> • using namespace std;
void menu(int &shapeChoice, ofstream &writefile); • //post: determines shape • void getLengths(intshapeChoice, double &radius, double &height, double &width, double &length, ofstream &writefile); • //post: gets lengths • void calculateVolume(intshapeChoice, double radius, double height, double length, double width, ofstream &writefile); • //pre: lengths must be >0 • //post: calculates volume • const double PI = 3.1415; • int main() • { • ofstreamwritefile; • writefile.open("Model4.dat", ios::app); • if (writefile.fail()) • { • cout <<"\n\nFilecannotbeopened.\n\n"; • exit(1); //program halts • }
Before filling in the main body of the int main, make skeletal functions with stubs. Here is how: • Copy each prototype one at a time. • You must leave out the semicolon or delete it after pasting. • Your choice about keeping conditions. • Paste each prototype below the last close brace } of int main(). • Under the function header just pasted, enter an open brace { , press return twice, and enter a close brace } . • This is a skeletal function. • Between the braces enter a simple cout statement identifying the function. • Example: cout << “Menu \n\n”; • This is a stub. • Why do this???? • After the int main() is coded, you can run the program then and run it again at later stages of the program where other functions are called. • If there are any errors in the function headers or call statements or int main(), they are easy to find and fix. • After the program is running perfectly with skeletal functions and stubs, code one function at a time. Any errors found will be only in that function and easy to locate and fix. • In larger programs this is the only way to prevent “hitting the wall” in debugging.
Finish the int main() • intshapeChoice; • double radius, height, width, length; • boolisRerunning = true; • string answer; • while (isRerunning == true) • { • menu(shapeChoice, writefile); • getLengths(shapeChoice, radius, height, width, length, writefile); • calculateVolume(shapeChoice, radius, height, length, width, writefile); • cout<<”Wouldyoulike the volume of anotherfigure? (y/n)\n”; • cout<<”Press y for yes or n for no. ”; • cin >> answer; • if (answer == ”n”) • { isRerunning = false; • } • } • writefile.close(); • return0; • }
Menu Function() • void menu(int &shapeChoice, ofstream &writefile) • { • cout<<"\tCalculating the Volume of Shapes\n\n"; • writefile<<"\tCalculating the Volume of Shapes\n\n"; • cout<<"For what type of shape would you like to calculate the volume?\n\n"; • cout<<" 1.Sphere\n"; • cout<<" 2.Rectangular Prism\n"; • cout<<" 3.Cone\n"; • cout<<" 4.Cube\n"; • cout<<" 5.Cylinder\n"<<endl; • writefile<<"Forwhatshapewouldyoulike to calculatethevolume?\n\n"; • writefile<<" 1.Sphere\n"; • writefile<<" 2.Rectangular Prism\n"; • writefile<<" 3.Cone\n"; • writefile<<" 4.Cube\n"; • writefile<<" 5.Cylinder\n"<<endl; • cin>>shapeChoice • }
void getLengths(intshapeChoice, double &radius, double &height, double &width, double &length, ofstream &writefile) { do { if(shapeChoice == 1 || shapeChoice == 3 || shapeChoice == 5) {cout<<"Please enter the radius."<<endl; cin>>radius; cout<<"The radius is "<<radius<<"."<<endl; writefile<<"The radius is "<<radius<<"."<<endl; if(shapeChoice == 3 || shapeChoice == 5) { cout<<"Please enter the height."<<endl; cin>>height; cout<<"The height is "<<height<<"."<<endl; writefile<<"The height is "<<height<<"."<<endl; } }else if(shapeChoice == 2) {cout<<"Please enter the width."<<endl; cin>>width; cout<<"The width is "<<width<<"."<<endl; writefile<<"The width is "<<width<<"."<<endl; cout<<"Please enter the height."<<endl; cin>>height; cout<<"The height is "<<height<<"."<<endl; writefile<<"The height is "<<height<<"."<<endl; }else if(shapeChoice == 4) {cout<<"Please enter the length."<<endl; cin>>length; cout<<"The length is "<<length<<"."<<endl; writefile<<"The length is "<<length<<"."<<endl; }else {cout<<"You did not enter a valid choice.\n"; writefile<<"You did not enter a valid choice.\n"; } } while(height<0 || width<0 || radius<0 || length<0); }
void calculateVolume(intshapeChoice, double radius, double height, double length, double width, ofstream &writefile) { cout<<"Calculating the volume of #"<<shapeChoice<<endl; writefile<<"Calculating the volume of #"<<shapeChoice<<endl; switch(shapeChoice) { case 1: cout<<"The volume is: "<<(4/3)*PI*pow(radius, 3); writefile<<"The volume is: "<<(4/3)*PI*pow(radius, 3); break; case 2: cout<<"The volume is: "<<length*width*height; writefile<<"The volume is: "<<length*width*height; break; case 3: cout<<"The volume is: "<<(1/3)*PI*pow(radius, 2)*height; writefile<<"The volume is: "<<(1/3)*PI*pow(radius, 2)*height; break; case 4: cout<<"The volume is: "<<pow(length, 3); writefile<<"The volume is: "<<pow(length, 3); break; case 5: cout<<"The volume is: "<<PI*pow(radius, 2)*height; writefile<<"The volume is: "<<PI*pow(radius, 2)*height; break; default: cout<<"You did not select a shape.\n"; writefile<<"You did not select a shape.\n"; cout<<"PLease enter a number from 1 to 5\n"; writefile<<"PLease enter a number from 1 to 5\n"; } }