cout << wages * TAX_RATE;
cout << first_name << " " << second_name << "\n";Do NOT forget the semicolon(";").
double x;
int count = 0;
int student_number = 1;
cin >> wages;
An assignment changes the value of a variable.
b = 2*a;
This means:
a = a+b;
b = 2*a;Always work out even simple sequences of assignments, step by step, on a piece of paper.
Never guess what a series of assignments do, until you have tried them out, step by step, on a simple example, using pencil and paper.
Example. What happens to integer a and b if they both start with value 1 and this seqence is executed
a = a+b;
b = 2*a;
a = 3*b +2*a;
Solution using equalities:
Table
| Step | State of memory |
|---|---|
| Before | a = 1, b = 1 |
| After a=a+b; | a = 2, b = 1 |
| After b=2*a; | a = 2, b = 4 |
| After a=3*b+2*a; | a = 16, b = 4 |
Abbreviated solution using a table of values:
Table
| Step | a's value | b's value |
|---|---|---|
| Before | 1 | 1 |
| After a=a+b; | 2 | 1 |
| After b=2*a; | 2 | 4 |
| After a=3*b+2*a; | 16 | 4 |
This process is called tracing and is very useful when trying to figure out code.
Two exercises -- assume that a,b,c,... are ints.
Exercise: What happens if we start with a equal to 1 and b equal to 2?
a=b;
b=a;[ trace0.cpp ]
Exercise: What happens if we start with a equal to 1 and b equal to 2?
c=a;
a=b;
b=c;[ trace1.cpp ]
Always trace simple sequences of assignments, step by step, on a piece of paper.
tax = TAX_RATE * wages;
const int MINUTES_PER_HOUR = 60;
const double INCHES_PER_FOOT = 12;
const double TAX_RATE = 30.0/100.0;
sqrt(b*b-4*a*c)
cout << 1/2;
+++ You will note that I automatically write a half as 0.5 in my code. I've learned to not write 1/2. Since this went wrong in languages like FORTRAN and Algol in the 1960s. Also I know that multiplying is faster than dividing and so "xxx*0.5" is faster than "xxx/2".
Refactor working code one small edit at a time. No clever steps! And repeat all the tests after each small change.
Write up and hand in one of these exercises and your solution, with your name, for me to grade, before the start of class.
Start by downloading [ project.cpp ] and thinking about what you have to change -- for example putting in your name.
Ideally you should then edit the file to fit one of the programming projects in chapter 1 of the text, compile, run, debug, and hand in a print out of the program at the start of the next class.
But if you are in the second lab you won't have met the tools... So you can (0) work out how to use them on your own, OR (1) edit it on your own machine and print the result, OR (2) print it out here and mark up the changes you will work and hand that in. In these cases resubmit the completed project next week.