W2 - variables and expressions
January 19, 2021
1 Week 2: variables and expressions
Reading: Chapter 2 in zyBook “Programming in C++” by Vahid and Lysecky.
[2]: // Setup cell
#include <iostream>
using namespace std;
Define variables:
Why do we need variables?
Variable life cycle: declare, initialize, use/modify.
1.1 Example
Zorg owns a circular parcel of land with radius 25 m. How much land does he own? Output the
area in m2 . Formula: A = πr2 .
[3]: // use 3.14 for pi
cout << (3.14*25*25) << endl;
1962.5
Zorg’s sister, Zerga, also owns a parcel of land with radius 75 m. How much land does she own?
The calculation is the same, but with different data. Make it general.
Declare variable radius: type variable_name; Initialize radius: radius = expression; OR cin »
radius; Use radius: simply write expressions using radius as argument, as many times as needed.
[7]: // what type of variable to use? int, float, double?
long double radius;
// assignment or cin?
cout << "Please enter the radius of the lot (in m)" << endl;
cin >> radius;
cout << "The area is " << 3.14*radius*radius;
Please enter the radius of the lot (in m)
75
The area is 17662.5
1
Digression: What types can we use for variables?
Example (cont). Landowners must pay taxes annually. These are calculated at \0.5peronem^2$
of land owned. Calculate Zorg’s tax:
[ ]:
Sisters have a different tax rate. Having to put up with their brothers, sisters’ rate is \$0.4.
Calculate Zerga’s tax:
[ ]:
Zorg purchases another plot of land. It is rectangular this time. Calculate Zorg’s tax now.
[6]:
The local government is eliminating cents. Output Zorg’s tax by dropping the fractional part. For
example, if the tax owing is \$25.72, output only \$25.
[ ]:
In an even wackier move, the government accepts only ammounts that are multiple of \$10. For
example, if the tax owing is \$237.81, then the tax payable is \$230. Calculate the tax payable in
this case.
[ ]:
Digression: given a floating point value stored in variable named x, calculate and output x rounded
to the nearest integer. Do not use branching (if statements).
[ ]:
1.2 Other examples
Any examples you would like additional practice with?
[ ]: