CMPSC 201
Ch. 3 Notes
Objective #1: Evaluate and use C++ assignment statements.
- The general form of an assignment statement is
variable = expression;
where the resulting value of the right-hand side of the statement is assigned
to the variable on the left-hand side. The expression could be a constant
such as 2.34 or an expression such as (salary
+ 4) * 2
- In an assignment statement, the equals symbol (=)
is used as the assignment operator. The assignment operator has lower
precedence than any other arithmetic operator so the expression on the right-hand
side is always fully evaluated before the actual assignment occurs.
- An assignment statement can be of the form
variable1 = variable2 = variable3 = expression;
where the assignment operator uses right-to-left associativity. That is, variable3
will first be assigned the value of the expression, and then variable2
will take on that value, and finally variable1
will take on the same value.
- C++ will use implicit type conversion (i.e. promotion) if
the data type of the value of the right-hand expression is not the same as
the data type on the left-hand side. For example, if wholeNumber
is an int variable, then the assignment statement
wholeNumber = 2.88;
will assign the integer variable 2 to the variable wholeNumber
(i.e. truncation occurs).
On the other hand, if the variable realNumber
is a double, C++ will change an integer expression into a floating-point value
upon assignment in the statement
realNumber = 5;
That is, realNumber is the floating-point
double value 5.0 rather than 5, the integer.
- In the case of mixed-mode expressions where one variable or value
is of a different data type than the other, C++ converts both to doubles in
order to perform the calculation but then implicitly typecasts the result
to the data type of the variable on the left-hand side. If finalResult
and anInteger are integers and aDouble
is a double,
finalResult = (anInteger + aDouble);
then the statement above causes anInteger
to be temporarily promoted to a double for the purposes of the addition, and
then the result is truncated so that it can "fit" into the integer
variable finalResult.
- C++ includes a few compound operators (sometimes referred to as "shortcut
assignment operators") including +=,
-=, *=,
/=, and %=.
For example, the assignment statement
total = total *3;
is equivalent to
total *= 3;
Objective #2: Identify and use accumulator statements.
- An accumulator statement is used to obtain running totals where the
added value changes each time. The general form for such statements is
variable = variable + newValue;
- Accumulator statements will often be used within loops later in this course.
Objective #3: Identify and use counter statements.
- A counter statement is used to obtain running totals when a fixed
value is being added to the running total.
variable = variable + fixedValue;
- Often, counter statements are used to add one to a running total
so a common counter statement is
count = count + 1;
- Counter statements will often be used within loops later in this course.
Objective #4: Use the incrementing and decrementing operators.
- The incrementing operator ++ is
used to add one to a variable.
- The decrementing operator -- is
used to subtract one from a variable.
- Note that the following statements are equivalent:
count++;
++count;
count = count + 1;
count += 1;
Objective #5: Use the common stream manipulators including setw,
setprecision, setiosflags,
dec, hex,
and oct in order to format outputted data.
- In order to display numerical output nicely with C++, it is useful to use
the stream manipulators setw, setprecision,
and setiosflags. For example, you
can use setw to force C++ to set an certain
field width. This allows you to line up numbers in a column for example. See
Programs 3.5 & 3.6 on pp. 118 & 119 for an illustration. However,
if the field width specified by setw is too
small, C++ will ignore that manipulator and display all of the value rather
than truncating or rounding the value. Also, realize that the setw
manipulator only applies to the next value in the stream. Therefore,
cout << setw(3) << 1 << endl;
cout << 23 << endl;
cout << 456 << endl;
would not cause the three values as displayed by three separate cout stream
insertions to be lined up in a right-aligned column. However,
cout << setw(3) << 1 << endl <<
23 << endl << 456 << endl;
would line up the three values in a column since the setw manipulator applies
to the whole cout stream.
- In order to force C++ to display a floating-point (i.e. decimal) value in
the conventional format rather than exponential notation, you can use the
setiosflags(ios::fixed) manipulator in a
cout statement. For example,
double c = 3e8;
cout << setiosflags(ios::fixed) << c;
causes 300000000.000000 (with default 6 decimal
places of precision) to display rather than 3e+008.
- In order to force C++ to round a number to a given decimal place, it is
convenient to use the setiosflags and setprecision
manipulators together. For example,
double pi = 3.141592653;
cout << setiosflags(ios::fixed) << setprecision(3) << pi
<< endl;
causes 3.142 to display with exactly 3 places after the decimal.
Unlike setw, the manipulators setiosflags
and setprecision do apply to all stream insertions
that follow them. Therefore you can use setiosflags(ios::scientific)
will cause following floating-point values to be displayed in exponential
notation.
- The iomanip.h header file must be
included at the top of a program in order to use stream manipulators such
as setw, setprecision,
and setiosflags.
- See Table 3.1 on p. 118 and Table 3.2 on p. 120
Objective #6: Use the common math library functions appropriately including
sqrt, abs,
fabs, pow,
sin, log,
floor, ceil,
and exp.
- Many mathematical functions are built-in to C++ if you include the
math.h header file at the top of a program. Such built-in or predefined
functions are called library functions as opposed to user-defined functions
that you will later learn to create from scratch.
- You can compute the square root of 123 and store that value in the variable
myRoot with the statement,
myRoot = sqrt(123);
Of course, you can also compute the square root of a variable with the sqrt
library function as in:
hypotSquared = 25;
hypot = sqrt(hypotSquared);
- See Table 3.4 on p. 133. Study those functions and practice using them in
a C++ program. Be aware of their existence and be able to use them for the
duration of this CMPSC 201 course.
- Two other useful mathematical library functions are floor and ceil. The
floor function truncates positive floating-point values. For example,
cout << floor(3.99);
causes 3 to display. However, it should be noted that for negative values,
truncation technically does not occur. For example,
cout << floor(-3.99);
causes -4 to display.
The ceil function causes the next largest whole number to display. For example,
cout << ceil(2.01);
causes 3 to display and
cout << ceil(-2.01);
causes -2 to display.
- The library function fabs is used to take
the absolute value of a floating-point value. For example, the following statement
displays 2.34
cout << fabs(-2.34);
whereas the following statement displays 2.
cout << abs(-2.34);
Objective #7: Use the cast operators to explicitly perform type conversions
when necessary.
- Sometimes, you may want to change the data type of a variable within a program.
This technique is called casting or typecasting. It is done
explicitly by the programmer.
- You use the cast operators to typecast within a C++ statement.
int weight = 185;
const double LB_TO_KG = 2.205;
cout << "You weigh " << int (LB_TO_KG * weight) <<
" kilograms.";
causes the display of,
You weigh 407 kilograms.
The int casting operator changes the 407.925
into an integer, essentially truncating the 0.925 from the product of LB_TO_KG
times weight.
In the statement,
char charValue = 'a';
cout << int (charValue) << endl;
causes the integer value 97 to display since 97 is the ASCII value of a lowercase
a.
the int is the cast operator and is being applied to the variable charValue.
Objective #8: Use the cin object to input data.
- The cin object is used to obtain data from
the input stream. Often, it is used with the input operator >>
which is also known as the extraction operator (because it is used to extract
data from the input stream.)
- In the statement,
cin >> userNumber;
the value inputted by the user into the keyboard will be stored in the variable
userNumber. By the way, the c in "cin"
stands for console and the in stands for input. Therefore, cin
is associated with the standard console input device which is usually considered
to be the keyboard.
- The statement,
cin >> userNumber1 >> userNumber2
>> userNumber3;
could be used to obtain three values supplied by the user as long as he types
blank spaces or return characters between each entry.
- Please note that it is not syntactically correct to use endl with cin
statements as you do with cout statements.
The following statement is invalid:
cin >> userNumber >> endl;
Objective #9: Declare and use constants appropriately.
- The const qualifier (keyword) is
used to create a constant identifier. This should be done at the beginning
of the function in which it is to be used (or in some cases as a global constant
before the main function.) Constants are not considered variables and cannot
be assigned new values later in the execution of the program.
- Constants are convenient so that the programmer does not have to type a
specific value throughout a program since it is easier to remember the name
of the constant. Also, if the constant needs to be changed in the future,
it's value only needs to be changed in its declaration/initialization statement
at the top of the program.
- It is convention to name constants with all uppercase letters, separating
words with the underscore character. This makes your constants stand out more
so that other programmers (and you) can find constants in your code more easily.
Our course Coding Standards require
you to use this format for naming constants. For example,
const double PA_SALES_TAX = 0.06;
- It is often convenient to include the header files limits.h and float.h
at the top of a program since they include a few C++ built-in constants that
are convenient to use.
Run the program:
#include <iostream.h>
#include <limits.h>
#include <float.h>
int main()
{
cout << INT_MAX << endl;
cout << INT_MIN << endl;
cout << DBL_MAX << endl;
cout << DBL_MIN << endl;
return 0;
}
to examine the maximum and minimum values for the int and double data types
on your computer platform. For Win NT 4.0, Win 95, Win 98 and most other
32-bit Windows platforms these values are:
INT_MAX = 2147483647
INT_MIN = -2147483648
DBL_MAX = 1.79769e+308
DBL_MIN = 2.22507e-308
CMPSC 201