rec03, online portion
to be done before going to lab 03

Arithmetic Operators and Expressions
Formatting with Manipulators and Methods
(intro to objects)
Errors and Debugging

Topics

- Introduce bugs and learn to read and understand compiler errors
- Learn the keyboard shortcuts for Compile, Build and Execute
- Learn that the following should never happen if you always write correct code:
- Fix bugs (one at a time!)
- Fix errors of style (variable names)
- Fix errors of a bad user interface (UI)
- Fix errors involving comments and style and problem breakdown
- Predict the output of arithmetic expressions, using the +, -, /, * and % operators
- Run the program:
--- to see if your output matches the predictions you made
--- this is fixing errors that only appear in the output - logic errors, programmer errors
- Introduce a linker error and learn to read and understand linker errors
- Continue learning the Debug facilities
- Manipulators and methods
- const
- arithmetic for rounding
- compound assignments
- writing a whole program on your own

rec03

Task 1: World's tiniest complete program - correctly identified as yours.

In many Tasks in rec03 you'll be fixing bugs.
Fix only the things that the Task says to - don't fix anything else.
If you do more than what a particular Task says to, later Tasks won't make any sense - you will have already done them without knowing what you were doing!

Be sure you work from this page - not the answer key.

Create a new project, "FMLrec03online", and a C++ program, "rec03.cpp" (where FML are your initials as you have learned in previous recitations).

Every program you create for this course must have identification comments appearing at the beginning of your program.
We give you a boilerplate version that you must use. For this Task, practice getting text we require from the web, placing it in your program and then modifying it to have the right information for you. We'll use the link for homework identification. Make sure your correctly modify it. (E.g.: this is rec03, not hw##.)

Use these ID comments as the very first things in your program. - Yes, even before any #include directives.

Write the shortest possible main() function. It must will compile, link and run but do nothing.

After copying and modifying the ID comments you should have a program that has the correct identification comments at the top and a complete main() function - but there will be no output and no input and no calculations and no assignments.

Will this program run?
Does this program need return 0;
Does this program need #include <iostream> or using namespace std; ? Why (or why not)?

As always, try to write this program and test it by compiling, linking and then running before looking at the answer key.

If you are trying to write the tiniest program - don't the comments count?

Answer key for Task 1

Task 2: Copy our code. Fix our errors

In this Task you will copy our code into you program and then attempt to compile it. It has syntax and other errors so that you can learn how to debug - the process of removing errors. You will be reading the error messages (one at a time of course) to see if you can figure out what the problem is.

When it is time to copy our code, you MUST COPY from this document and PASTING it into your source code file. (The code you will copy is given below.) DO NOT TYPE IN OUR CODE.

Don't start copying until we tell you to below. Keep reading.

After you have copied our code into your program - Do NOT fix these errors immediately. Instead, save your file and compile your program, looking at the error messages generated. Also don't write or add any other code to what you have copied and pasted this into your source file.

FIX ONLY ONE ERROR AT A TIME (even if you see something that you know will cause an error).

Review from rec01 && rec02: HOW MANY ERRORS ARE THERE IN ANY PROGRAM THAT HAS ERRORS? (Correct answer: only one, the first one.) Fix the ONE error, save, then recompile to test if you have gotten rid of all the errors.

It will help you if you read the labels on the output so that you know what the programmer who wrote this was trying to do. That programmer could have helped us even more by writing comments.

As you read the error messages, make sure BEFORE you try to fix the error, that you understand what the error message is saying. Sometimes it's very hard to figure out but some words you should be learning, like identifier and undeclared. Recall also any rules of the C++ language (like valid identifiers for variable names).

For this Task, you do not need to attempt to do all the steps to create an executable program. You only need to compile the program so that the compiler can check for errors. Recall that this is done in VC++.NET by hitting Control-F7 (hold down the Control key while tapping the F7 key). You can also do this by pulling down the appropriate menu and selecting Compile... (but keyboard shortcuts are much faster!).

Hopefully in the future as you enter code, you won't make these kinds of mistakes.

After you have debugged this code, fixing only the compilation errors it gave you, look at the answer key to see what your code should look like at the end of this Task. You should not fix anything other than the compilation error the IDE tells you about.

Below is the fragment to copy. After copying and pasting into your main, save.
Until there are no more errors, the sequence is:

OK, Now (finally!) copy the code from below into your main() function and work with it as described above. If there is an error message or warning message that you do not understand, write it down and ask your lab worker for help at the next lab - but do this AFTER you've tried to understand the message.

Here is the fragment to copy, mistakes and all:
---------------------------------------------------------------------------------------------------------------------------

    int Num1, 2Num


    // Write output on the screen

    cout << "Please enter the values for Num1 and Num2: ";
    cin << Num1, Num2;
    x = Num1 + Num2 / 2;
cout << "The sum of " << Num1 <<   and " << Num2 << " is ";
cout << Num1 + num2; << endl;
     cout << "The quotient of " << Num1 << " and " < Num2 << " is ";
     cout << Num1 \ Num2 << end l;
          cout << "The remainder of" << Num1 << "divided by" << Num3 << 'is';
          cout << Num1 mod Num2 << endl;
    cout << "The product of " << Num1 << " and " << Num2 << " is ";
    cout << (Num1)(Num2) << endl;
    cout << endl;
    cout << endl;
    // Show the product of the values entered.
    cout << "The difference of " << Num1 << " and " << Num 2 << " are ";
    cout >> NUm1 - Num2 >> endl;
    // Calculate the average of the two inputs
    cout << double x; << endl;

---------------------------------------------------------------------------------------------------------------------------
Answer key for Task 2


Task 3: It compiles! Now FIX it?

Now that you have a program that has no compilation errors or warnings in it - Fix it! (Right about Now you'll probably be saying What?)
There are errors that are not syntax (compiler) errors - your program is not "good" until all the errors are fixed. But (you'll complain) my program is a good program because it compiles! NO, it's not good yet - it just compiles without errors which is important but just the first step. Style is a very important part of your program. It must be readable, not all jammed up, must have lots of "whitespace" and each subpart of the problem must be clearly indicated by blank line and comments describing each subproblem's solution. It must also follow any style guidelines required. When you work for a company, you'll probably be given a stylebook showing the way the company wants your code to look.

For this course (so far) you should know that identifiers (names you choose) for variables should start with lowercase letters; should never have underscores and if there are multiple "words" each "word" after the first should be capitalized (they must also follow the 'rules' for identifiers you noticed in the previous Task - did 2Num follow the rules for identifiers?) A good variable name also gives a hint to how it is being used. What's a x used for? It is a variable name in this program - oh no!

There is still no need to run the program - just do the compilation step. Yes, we will eventually actually run the program - but only when it is completely good.

Go back and fix the variable names so that they are in good style and would help another programmer understand the meaning of the data they hold.

From Now on, get in the habit of doing things right AS you write your code, not fixing them later like you are doing Now.

When you think you have corrected all the bad variable names, check your code against the answer key. In the answer key, changes are shown in red. There are also some explanatory // comments in red which can be removed after you understand what they say.

Answer key for Task 3


Task 4: Now it compiles and it has good variable names. Now FIX it!

Is the indentation correct? Why does this matter? One part of readability means that another C++ programmer can look at your code and quickly and easily see what is what. In the main() function, the { and } show where main's block (or body) starts and ends. For this course, we require you to show visually what's inside the { and } You do this by indenting everything consistently. You should never have any statements jammed over to the left hand side inside a pair of { and }. There will be more style guidelines as we progress but for Now, correct the indentation of the statements inside main() making them all the same distance from the left hand side. In the IDE the TAB key is perfect. If you place one TAB before each of the statements in main, after removing all the spaces of course, that will be perfect.

Also, try this: move the cursor to the end of a line and hit Enter. Watch the cursor move to the next line and automatically indent one TAB. Great!

For things outside of main() (like the ID comments at the top), don't indent.

If you copy and paste into your program from any other source fix the indentation right then to match your program's style. (And of course you'd only copy after reading and understanding the code.)

Get in the habit of always correctly indenting your code AS you write it, not later.

Now, fix the indentation of your code for this Task.
Look at the answer key to see if what you did matches ours.

There also might be a warning about main() not returning a value.
Warnings are not error but they must be carefully read to learn why they are being flagged.
return 0; in the main() function is not required by the definition of the language.
If you want to add it now, you may.

Answer key for Task 4

Task 5: Now it compiles, is nicely indented, has good variable names - Now what? Comments

Are the comments good? Comments should explain what the code is doing, not how C++ works. Comments are read by C++ programmers. They should know that cout << does output. Why some output was done or what was output is what a comment should explain, not that output was done.

Comments should also be right. Check that the programmer who wrote this code does what her comments say she meant to do. If the comment says that a number will be divided by but it is actually divided by 5 - something is wrong!

Fix all bad comments. Check your work against the
Answer key for Task 5.

Task 6: Are we done yet? Could another programmer SEE the subparts of the problem by looking at main()?

From Now on you'll know to always write code correctly AS you write it - no need for going back to fix things. The kind of problems you are fixing in this Task would never appear in your code because you would have solved the problem first by subdividing it into parts and written your code accordingly.

Recall that style includes readability and is used to show the different parts of your programs. If there are five top level steps in the problem, your program's main function must show this. (Later you will do this with functions.)

You'll need to go back and add blank lines and comments so that someone else (another programmer) reading this code can easily see what the different parts of the program are - they should be able to understand what's happening by reading ONLY the comments. How did this programmer break the problem into pieces - that should be very easily seen by sectioning off the parts.

Usually you are the one who breaks the problem into subparts before you start writing any code. For this task, you'll have to try to figure out the subparts that that other programmer who wrote this was trying to show and add comments appropriately. (That other programmer was us, of course!)
In this task you should also make sure that the different subproblems are actually grouped together in the code. For example, all the code for doing the fourth part of the problem should be together - if one line of code for subproblem four appears in subproblem three - even if it compiles, links and runs, why is it there?

From Now on, get in the habit of doing things right AS you write your code, not fixing them later.

Find the errors of this sort in the code and fix them. Check yours against the
Answer key for Task 6.

Task 7: What else should you always do correctly while writing your code?

There are some other errors. At this point you are probably saying: "but it works - and I even made it readable and well commented - what's wrong Now?"
OK.
Does the UI (the user interface) work? Will a user who is not you like the way it looks? like the way she is prompted? Is the output well labeled so that the user knows what the output values mean?

Are there spaces between words and values or are they all jammed together? Is every output well labeled? Is each prompt clear as to what is being asked for by the programmer?

And another point. Recall the user is not you.
The user must not need to know anything about the inner workings of your program.
Is there a prompt in the UI that assumes that user knows things she shouldn't? The user can only be asked for things that you, the programmer, need. The user can never need to know anything about things like the names of your variables! Fix this too.

Get in the habit of designing your UI before you write any code. It's easier than fixing things later.

Since we want to see what the UI actually looks like in the console window, we'll need to do more than just compile to check for syntax errors - we'll need to actually run the program.

As a review, recall that there are actually these steps before you can run a file:

Look carefully at the black input/output window as you pretend to be the user.
Is everything nicely spaced? Is every output well labeled? Are input values consistently taken from the same place (are some taken on the same line as the prompt and others on the next line? - oh no)? These sorts of things are details but many a good program has never been commercially successful due to a badly designed UI.

If anything doesn't look nice, go back into the editor and fix it, save it and rebuild and run the executable.
Keep doing this until everything in the UI looks nice.

Run our code to see how the answer key works the UI.
Answer key for Task 7

Task 8: Ah! The program finally is good! Wait - have you thoroughly tested your code?

If the user enters the values 15 and 2 what will be the values of the sum, quotient, remainder, product and difference? Write your predictions on paper first. Check your answers against the Answer key for Task 8 but don't run your program yet to see if you got the right values in the output.
Be sure you notice the correct way to cast types using static_cast<>().

Task 9: Finally? (I hope I hope I hope) - How carefully did you read your output?

Now run the program and check your guesses. The output values should be the same as in the previous task.

READ your output very carefully.

It is a very common error for a programmer to quickly check the output and miss an error - but then to go ahead and turn in the program! Don't make this mistake. If the values output by the program are not correct, see if you can figure out why and make corrections.

Are all the values correct? What about the average?
What's wrong? (Hint: precedence of operators)

Did this work? What might still be wrong? (Hint: / and ints)
Recall: explicit coercion
Recall: cast
(These are terms you should know)

Go back and fix your program. Then check the
Answer key for Task 9

Task 10: Introduce a linker error and observe it.

Change the name of your main() function to myMain().
If you do not have the statement return 0; at the end of the function, add it there.
[ It's normally not needed in main(), but since we are messing things up, it will cause even more errors than we want you do deal with - so add it even though it is optional in main() ].
Save (Crtl-S)
Decide the answer to the following questions before trying to compile, link or run.
Will your program compile?
Will your program link?
Will your program run?
Now go to the

Answer key for Task 10


Task 11: Now that you have seen many kinds of errors, how can you make sure that you NEVER do these things.

You should always take care of these sorts of things while you are writing your code.
Always write perfect code - including, style, good names, indentation, readability. comments and so forth - Oh, and no syntax errors either, please.

Answer key for Task 11

Task 12: An even nicer UI - formatted real numbers : invoking methods on objects

Make the display show three decimal points for all the real numbers.

Test that your program works even if the user enters two numbers that when divided give a number with .000 as the decimal part (if the user entered 3 and then 3, 1.000 should be displayed, not 1.). Did you get the decimal point to appear even in these cases?

Note that thorough testing is always needed when you are a programmer. You should try to test the program so that all possible outcomes are tested - it's not always possible but it's the ideal.

Be sure you read the text in the answer key as it explains how to format as well as how the cout object works for formatting.

Be sure to read all the answer key as there is information you need to learn there.
Once you have gotten you code to show 3 decimal places for all real numbers, check our answer by going to the
Answer key for Task 12

Task 13: Now show scientific notation for real numbers

Modify your code to show real numbers in scientific notation and change the precision to 7 to see how this affects the output.
After you've check this out, put things back to show fixed with 3 decimal places.

Answer key for Task 13

Task 14: using manipulators instead of methods

Sometimes we need to set formatting within a sequence of <<'s. Yes, we could write a separate line for each but sometimes it's clearer if there is only one cout that all the output is going into. There are other times when this is needed.

We use manipulators for changing the format within a sequence of <<'s.

You've actually used a manipulator already: endl. It is not a character or a string. It's a manipulator.

A manipulator is a thing that when sent into an output object (like cout) causes the object to change somehow or to do something. The endl manipulator causes the cout object to move the cursor to the start of the next line.

THE REST OF THIS TASK IS OPTIONAL.
It deals with details of formatting that you are not required to know
Go on to Task 15 now if you do not want to do this part.

Write code that will allow the user to enter three real numbers and their presentation widths and use that information in the display:

Please enter three real numbers: 3.1234 425.1 5.12345.

Please enter the minimum width for each: 10 15 8

The numbers are:

    3.1234,       4.251e2, and  5.12345.

Note that there are three different precisions (4, 3, and 5) and a change from fixed to scientific and back when we show the user the numbers entered. The first value is shown in a width of 10, the second in a width of 15 after the comma, and the third in a width of 8 after the ", and ".

endl is defined in the iostream header. Are all these manipulators?

Write the code for this Task at the end of your program, just before the return 0; test it and then look at the
Answer key for Task 14


Task 15: Just when you thought you had a good program: Run time errors

For this Task, you must be work with the code given below.
Replace all your source code after your ID comments with the code below.
Do this by:

#include <iostream>
using namespace std;

int main() {

    int num1, num2 ;

    // Prompt for and get two inputs
    cout << "Please enter two integer values: ";
    cin >> num1 >> num2;


    // Show the sum, quotient, remainder, product and difference
    // of the values entered.
    cout << "The sum of " << num1 <<  " and " << num2 << " is "
         << num1 + num2 << endl;

    cout << "The product of " << num1 << " and " << num2 << " is "
         << (num1)*(num2) << endl;

    cout << "The quotient of " << num1 << " and " << num2 << " is "
         << num1 / num2 << endl;

    cout << "The remainder of " << num1 << " divided by " << num2 << " is "
         << num1 % num2 << endl;

    cout << "The difference of " << num1 << " and " << num2 << " is "
         << num1 - num2 << endl;

    cout << endl;


    // Calculate and display the average of the two inputs
    double averageOfInputs; 
    averageOfInputs = (num1 + num2) / 2.0;
    cout.setf( ios::fixed );
    cout.precision( 3 );
    cout.setf( ios::showpoint );
    cout << "The average of the two inputs is "
         << averageOfInputs << endl;

} // main

Task 16: Predict where a runtime error might occur. Test your hypothesis by RunToCursor.

Which line could cause a run time error?
Use the debugger to RunToCursor and then StepOver the line you predicted to see what happens in the IDE.
Remember in the debugger is a good time for this - after selling millions of copies of your software it a really bad time.

Also if you don't use the debugger for this Task, you may have to reboot your machine.

We are generating a serious error in a running program. Inside the IDE that's safe.

Use the debugger!

If you can't recall how to use the debugger at all, go back to rec02 and review.

Run To Cursor is done my placing your mouse pointer (cursor) on a line of code and then right-clicking.
Choose Run To Cursor from the choices.
The line that you place your cursor on to should Run To is:

    cout << "The quotient of " << num1 << " and " << num2 << " is "
         << num1 / num2 << endl;

While Running to Cursor, what values should the user enter to cause a runtime error?

What happened? You'll need to read the answer key to learn how to get out of this mess, so see the
Answer key for Task 16

Task 17: Write a complete C++ program for calculating tax amounts on restaurant bills. A REVIEW plus two possibly new concepts.

We estimate that this Task should take you about 20 minutes to write. Attempt to do this before looking at the answer key. You will not have an answer on a test. After you have written your version, go the answer key. Read the rest of this Task so that you know some of the issues you should be working on in this Task.

If you cannot do this Task in some form in about 20 minutes (not necessarily getting all the things we show in version TWO), we suggest strongly that you speak with your professor during office hours.

Ask the user for how much a restaurant bill is then display the amount of the tax on that bill. The tax rate for this problem is 8.25%. Remember good user interface, good labeling (nothing jammed together on the screen for example), good style and make sure that the amounts are correct.

For this problem we want you to store the right amount for the tax amount to two decimal places. The tax amount should be "rounded up" to the nearest penny. We want the value stored to have only two decimal places, not just be displayed that way. You will see the actual value stored in memory in the debugger. Since precision() causes the output to be displayed as if rounded off but doesn't change anything other than the display, you cannot use it to get just two decimal places stored into the variable for the tax amount.

Output and assignment are very different things! (and you better know the difference).

You'll have to use arithmetic (there might be several ways). There are also some built-in functions that you could use but for this problem just use arithmetic.

NOTE: There are three programs shown in the answer key for this Task.

Version ONE does things in a way that you should not do after you have learned the better ways.
Note particularly that your textbook often shows code the way we are asking you to never write code.

Version TWO does these things the right way. The C++ topics are: constants and compound assignment operators.
If you do not know how to do this Task in the second version's way, be sure you come back to it after you've learned these topics.

Version THREE does things using a very compressed form of arithmetic to show that it is possible but not preferred since it is really hard to read.

Read all three versions to see how they do the same thing. Notice how the the second uses consts and compound assignments. Get in the habit of working with const and compound assignment - even though your text will continue to not use the better C++ idioms.

If you cannot do this Task in some form in about 20 minutes (not necessarily getting all the things we show in version TWO), we suggest strongly that you speak with your professor during office hours.

Recall that using the debugger to step through your program is a great idea!

Answer key for Task 17

[Task 18 removed]

Task 19: More debugging - less useful though is:

OUTPUT as debugging

There are two ways to find runtime errors. Both involve trying to find the one line that caused the error.
Using the debugger is the preferred way since you are always in control.
The second way is using output statements to try to "find" where the error occurred.

In the second, less useful, but sometimes quicker to set up method, you place output statements in your code, run the program and see which of these "debugging" outputs was the last one to execute before the the program had the runtime error. This doesn't always work as the output sometime is screwed up before it actually gets to the screen when a serious error occurs in your program. Also, you should make these cout's appear obviously added for this purpose by using comments and by jamming them up against the left hand side of the program where no statements should ever be normally. This way it will be easy to go back and remove them when you've taken care of the error. We'll have you do this method after you have tried the second method.

In the Answer Key there is a version of a program with lots of these sorts of "debugging" outputs that should allow you to see how to use them. We wrote them for you and so all you need to do read the answer key program to see how it works. No need to run it.

We do not suggest that you use this method normally. We suggest that you always step through your programs in the debugger.

Now that you know you shouldn't normally use this method, you can read the
Answer key for Task 19



You should complete this online portion before going to the lab period for rec03.