53
4.1 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.

Output of a program RUN should be well-defined. Tell the user clearly what the output means

  • Upload
    inari

  • View
    55

  • Download
    0

Embed Size (px)

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

Page 1: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.1

• 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.

Page 2: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.2

Formatting Output & HOMEWORK• We can format output with the use of endl; and

the 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:

cout << 17 << endl;cout << 243 << endl;cout << 1428 << endl;cout << 9 << endl;cout << 241986 << endl << endl;

cout << setw(4) << 17 << endl;cout << setw(4) << 243 << endl;cout << setw(4) << 1428 << endl;cout << setw(4) << 9 << endl;cout << setw(4) << 241986 << endl;

Page 3: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.3

• Formatting Output & HOMEWORK• We can format output with the use of endl; and the

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”;

Page 4: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.4

• Formatting Output & HOMEWORK• We can format output with the use of endl; and the

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.

Page 5: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.5

Chapter 4 Selection Structures

if statementsif/else statements

Nested if or if/else within if and/or else statements

Page 6: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.6

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; }

Orswitch and case statements to be

discussed later.

Single alternative decisionor one-way selection.

Double alternative decisionOr two-way selection.

Page 7: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.7

Making Changevoid getCents(int &cents, 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;

}

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";}

Series of if StatementsExamine and discuss code.

Should there be a check forbad input. Why and where?

Page 8: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.8

• 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”)

Page 9: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.9

Relational Operators and Logical OperatorsUsed in if statements

Relational Operators• <• >• ==• !=• <=• >=ex: a > bIs a is greater

than b

Logical Operators» ! not» && and» || or

ex: a && b

True if a and b are true a || b

True if only a or only b are true or if both are true

Page 10: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.10

• 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

Page 11: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.11

 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

Page 12: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.12

 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 &&.

Page 13: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.13

if ( something is true) {

if (something different is true){ do something}else{

do something different}

} else

{if (another thing is true){

do something else;}

}

Nested if and/or elsestatements

Discuss all combinationsof these statements.

Page 14: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.14

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.

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;}

Page 15: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.15

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; bool isHot = 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.

Page 16: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.16

• 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;

Page 17: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.17

• 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; }

Page 18: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.18

• 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 ______.

Page 19: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.19

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, bif (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

Page 20: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.20

• 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".

 

Page 21: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.21

HOMEWORKWhat is output by the following (somewhat tricky) code

segment? Justify your answer in one or two sentences. int num = 5;int prod = 8; if (prod = num){ cout << "equal" << endl;}else { cout << "different" << endl;}  

Page 22: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.22

HOMEWORKThe 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;  

Page 23: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.23

HOMEWORK

Write a code segment which reads in two strings, and outputs the word "different" if the input values are different.

 

Page 24: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.24

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;} 

  

Page 25: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.25

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;}  

Page 26: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.26

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))  

HOMEWORK

Page 27: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.27

•The else if Ladder Or

else if Chain

Page 28: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.28

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.}

else if ladder

Multiple Alternatives

Your text callsit else if chain

Multiple Selections

Page 29: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.29

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.

int num;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 ? 

Page 30: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.30

4dvoid 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”;}

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.

Compare the series of if statements on next slide with this else if ladder. Why use each structure ?

Page 31: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.31

4a: Making Changevoid getCents(int &cents, 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;

}

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";}

Series of if StatementsExamine and discuss code.

Page 32: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.32

Homework

Write a two code segments which has a check for bad input in the previous two slides.

 

Page 33: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.33

•The SWITCH statement

Page 34: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.34

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 and case statements

Another structurefor 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.

Page 35: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.35

•switchcout<<“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.*/

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.

Page 36: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.36

• MORE ON SWITCH

{case 1: case 2:

cout << “small”; break;

case 8: case 9:

cout<<“big”;break;

default:cout <<“oops !”break;

}

Page 37: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.37

• MORE ON SWITCHSwitch (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;

}

Page 38: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.38

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;

}

Page 39: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.39

Switch statements are often used with a menu of choices.void operation(int fnum, int snum, int opChoice, 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”;

}}

Page 40: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.40

• 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:1. Write a code segment showing a check for

bad input on the first slide .2. Write a code segment showing a check for

bad input only for division on the second slide.

Page 41: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.41

•The if Statement and the while StatementThe if Statement and the while Statement

They have the same structure, however:

1. The body of an if statement is executed once when the if condition evaluates as true.

2. 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.

Page 42: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.42

• Semantics of while loopif (test) while (test){ { statements; statements; statements; statements;} }

test

Statement list

Next statement

true

false

test

Statement list

Next statement

true

false

Page 43: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.43

• 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.int main() **Note: The whole while loop and int a, b, c; call statements hsve to be string answer; between the if file fail() bool isRerunning = 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;}

Page 44: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.44

• 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;

Page 45: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.45

• void menu(int &shapeChoice, ofstream &writefile);• //post: determines shape• void getLengths(int shapeChoice, double &radius, double

&height, double &width, double &length, ofstream &writefile);• //post: gets lengths• void calculateVolume(int shapeChoice, 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()• {• ofstream writefile;• writefile.open("Model4.dat", ios::app); • if (writefile.fail())• {• cout <<"\n\nFile cannot be opened.\n\n";• exit(1); //program halts• }

Page 46: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.46

Before filling in the main body of the int main, make skeletal functions with stubs.Here is how:

1. Copy each prototype one at a time.• You must leave out the semicolon or delete it after pasting.• Your choice about keeping conditions.

2. Paste each prototype below the last close brace } of int main().3. 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.

4. 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.

Page 47: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.47

• Finish the int main()• int shapeChoice;• double radius, height, width, length;• bool isRerunning = true;• string answer;• while (isRerunning == true)• {• menu(shapeChoice, writefile);• getLengths(shapeChoice, radius, height, width, length,

writefile);• calculateVolume(shapeChoice, radius, height, length,

width, writefile);• cout<<”Would you like the volume of another figure? (y/n)\

n”;• cout<<”Press y for yes or n for no. ”;• cin >> answer;• if (answer == ”n”)• {

isRerunning = false;• }• }• writefile.close();• return 0;• }

Page 48: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.48

• 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<<"For what shape would you like to calculate the

volume?\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• }

Page 49: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.49

void getLengths(int shapeChoice, 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);

}

Page 50: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.50

void calculateVolume(int shapeChoice, 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";

}}

Page 51: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.51

Assignment: Problem Lab 4 and ChecklistThe next program is rather long but it has within it most of what we have learned so far. • It is a program that lets the user enter given values to calculate for an

unknown value for some frequently used formulas. • It should have some practical value for you in problem solving topics in

science and engineering.You have two choices:1. Key in the program your self. Do not copy and paste because there are

characters that do not paste correctly from the slides and create very hard to fix errors in the program.

12ptsa. Use the checklist on the next slide to recreate the program step by

step.b. Feel free to make any improvements you would like. c. If you make typing mistakes or omissions, the debugging experience

will teach you many times more about programming than getting it right the first time through. Be grateful for the time you have had to spend tracing the code.

2. You can use the Model 4 program or Lab 4 program as a template or guide to create your own useful program related to your major. Use the check list for this also. 3 to 5pts extra credit.a. 3 extra credit points for using one of the programs as a template and

just substituting your own specs, formulas, functions names, and descriptions.

b. 5 extra credit points for presenting a program using similar skills, but has completely your own personal stamp on it.

c. 4 extra credit points for a program that falls between the above descriptions for 3 and 5 extra credit points.

Total: 11 to 13pts.****See Ruberics on the last slide.*** ***The Lab 4 program is on separate slide show.****

Page 52: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.52

Assignment: Problem Lab 4 and Checklist

Checklist:1. Load your template. Save it with the name of the program (no

spaces) and .cpp2. Fill in the ID and Specs.3. Write or update the #includes (preprocessor directives).4. Write the prototypes for the functions.5. Write post conditions for all the functions.6. If a function uses variables that could possibly have bad data, then

write pre condition for the function. 7. If the variables can be any value then do not write preconditions for

the function.8. It is important to have a check for bad input in functions where it is

possible for a user to give bad input. 9. In the int main() do the following:

a. Change the name of output file in open statement in int main() to Lab4.datb. Declare the variable or variables that are being sent to the

functions.c. Set up a while loop like the one in the last slide or a for loop to

rerun the program. d. Write your function calls. Remember do not use void or data

types in these calls.10. Write the functions one at a time and test them as you go along11. Remember your writefile statements to show all output in the .dat

file. 12. Submit to me a folder with your name on it and containing both

your .cpp and .dat files.13. Be sure to give all permissions on the folder and the files inside the

folder.

Page 53: Output of a program RUN should be well-defined. Tell the user clearly what the output means

• 4.53

RUBRICS FOR ASSIGNMENT LAB 4• 4 pts for submitting the program.                    Total

4pst.• 2 pts for correct and attractive output.            Total 6pt• 2 pt  for ID and Program Specification.          Total  8pts.• 2 pts for correct indenting everywhere            Total

10pts• 2 pts for all permissions on folder & files inside Total

12pts

• 3 to 5 extra credit points for using Model 4 or the given Lab 4 programs as templates or guides for writing your own useful program related to your major. Total 15 to 17 points• 3 extra credit points for using one of the programs

as a template and just substituting your own specs, formulas, functions names, and descriptions.

• 5 extra credit points for presenting a program using similar skills, but has completely your own personal stamp on it.

• 4 extra credit points for a program that falls between the above.