CSCI 1110.005 - Lecture Notes
Chapter 3
Arithmetic Expressions, Function Calls and Output
Contents:
Arithmetic Expressions
-
Arithmetic expressions in C++ are made up of constants, variables,
operators and parentheses.
-
C++ expressions are similar to algebraic expressions except
they are written on a single line rather than in two dimensions:
a + b
c - d
in C++ is written as (a
+ b) / (c - d)
-
There are five basic C++ arithmetic operators:
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus (remainder after division)
-
Parentheses are used to group sub-expressions.
-
Operations are ordered according to standard algebraic rules
of precedence:
Highest precedence:
( )
* / %
Lowest precedence:
+ -
-
Whenever there are multiple arithmetic operators with the
same precedence, their order (associativity) is from left to right.
x -
y + z
means (x - y) + z
not x - (y + z)
-
Whenever an operation happens with two operands (values)
that are of the same type, the result of of that type. This means that
integer (char, int, short, long) operations, that would result in a fractional
answer, are truncated.
|
Expression
|
Value
|
|
10 / 2 * 3
|
15
|
|
10 / 3 * 2
|
6
|
|
10 % 3 * 2
|
2
|
-
Operations with floating operands (float, double, long double)
are not truncated:
|
Expression
|
Value
|
|
10.0 / 2.0 * 3.0
|
15.0
|
|
10.0 / 3.0 * 2.0
|
6.66666...
|
-
Mixed operations cause the integer value to be converted
to floating. This process is called coercion.
|
Expression
|
Value
|
|
10 / 3
|
3
|
|
10.0 / 3
|
3.33333...
|
-
Whenever a floating result is stored in and integer variable,
the result is coerced to an integer (truncated). Similarly if an integer
result is stored in a floating variable, the result is coerced to a floating
value.
someInt
= 4.8;
results in 4 being stored at someInt
someFloat
= 5 / 3; results in 1.0
being stored at someFloat
-
Type casting is used to explicitly convert form one
type to another:
someInt
= int(someFloat + 0.5); stores the rounded integer value
someFloat
= float(someInt) / 3.0; stores one third of someInt as a float
Function Calls
-
Flow of control specified the order in which instructions
will be executed.
-
A function call is a mechanism that transfers control
to a function.
-
A parameter list is a list of values that is used
to transfer data to and/or from a function.
-
To call a function, use the function name followed by a list
of arguments (parameters) enclosed in parentheses.
someInt
= Cube(2) * 10;
calls the function Cube with 2 as the parameter.
-
Function calls have precedence that is higher than multiplication
and division.
-
Functions that compute a result which is returned to the
calling program are called value returning functions.
-
Functions that perform some computation but do not return
a value are called void functions.
-
A value returning function can be used anywhere a variable
of that same type can be used.
cout <<
"The square root of " << x << " is"
<< sqrt(x) << endl;
-
There are very many functions which have been written and
kept in libraries. A partial list of the C++ Library Functions can
be found on page 103 and in Appendix C in the text.
-
To use a library function, you must determine where it is
defined and use a #include statement for the .h file where the
definition is found.
#include
<math.h>
. . .
x = cos(alpha) + sin(theta);
-
Data is passed to functions by position in the parameter
list, not by the name of the parameter.
int x = 10;
int y = 15;
int z = 20;
float area;
. . .
area = TriangleArea(x, y, z);
. . .
area = Triangle(x * x, y
- z, abs(z - x));
. . .
float TriangleArea(int sideA,
int sideB, int sideC)
{
. . .
}
Formatting the Output
-
To format a program's output means to control how it appears
visually on the screen or on a printer.
-
White space (spaces, tabs, blank lines, etc.) is very important
to the readability of output.
-
Space characters (or text labels) must be inserted into the
output stream to seperate data values.
int x
= 10;
int y
= 15;
int z
= 20;
. . .
cout <<
x << y << z;
would cause the following to be output to the screen:
101520
To make the output more understandable use the following:
cout <<
x << ' ' << y << ' ' << z;
-
endl is
used to end one line of output and cause the next output to begin at the
left of the screen on the next line.
int x =
10;
int y = 15;
. . .
cout <<
"x = " << x << endl << "y = " << y << endl;
will output the follow two
lines and the cursor will be at the beginning of the third line:
x = 10
y = 15
-
endl is a manipulator. Manipulators
are used only in input and output statements to control the appearance
of the data on the screen.
-
setw is used to set the width
of and output. It has an integer parameter that specifies the width of
the next output value. For the following example assume that ans
has a value of 33 and num has a value of 7132.
represents the space character.
|
Statement
|
Output
|
|
cout << setw(4) << ans
<< setw(5) << num
<< setw(4) << "Hi";
|
337132Hi
|
|
cout << setw(2) << ans
<< setw(4) << num
<< setw(2) << "Hi";
|
337132Hi
|
|
cout << setw(6) << ans
<< setw(5) << num
<< setw(3) << "Hi";
|
337134Hi
|
|
cout << setw(1) << ans
<< setw(5) << num
<< setw(1) << "Hi";
|
337134Hi
|
-
When specifying the width for a floating value, you must
include the decimal character as part of the width. The value 4.85
requires four places, not three.
-
Large floating values are printed in scientific (E) notation:
float x = 123456789.5;
cout << x;
will output a value such as 1.234567E+08 which
is interpreted as 1.234567 times ten raised to the eighth power.
-
To force C++ to use the more standard form of output for
smaller floating values, use the following statements before any floating
point output takes place:
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
The first statement ensures that floating point numbers
are printed in decimal form rather than scientific notation. The second
spacifies taht the decimal point should always be printed.
-
To control the number of decimal places to be displayed,
use the setprecision manipulator:
cout << setprecision(4) <<
x;
causes the value of x to be output with four decimal places.
-
Floating output examples:
|
Value of x
|
Statement
|
Output
|
|
310.0
|
cout << setw(10)
<<
setprecision(2)
<<
x; |
310.00
|
|
310.0
|
cout << setw(10)
<<
setprecision(5)
<<
x; |
310.00000
|
|
310.0
|
cout << setw(7)
<<
setprecision(5)
<<
x; |
310.00000
|
|
4.827
|
cout << setw(6)
<<
setprecision(2)
<<
x; |
4.83
|
Programming Style
-
As far as the C++ compiler is concerned, statements are free
format. They can appear anywhere on a line, more than one can appear
on a single line, and one statement can span several lines.
-
C++ programs are written for two types of readers - the compiler
and a person. People have a very difficult time reading programs that are
in free format.
-
Consider the following program:
// HouseCost program
// This program computes the cost per square foot
of
// living space for a house, given
the dimensions of
// the house, the number of stories, the size of
the
// nonliving space, and the total cost less land
#include <iostream.h>
#include <iomanip.h>// For setw() and setprecision()
const float WIDTH = 30.0;// Width of the house
const float LENGTH = 40.0;// Length
of the house
const float STORIES = 2.5;//
Number of full stories
const float NON_LIVING_SPACE = 825.0;// Garage,closets,etc.
const float PRICE = 150000.0;// Selling price less
land
int main(){float grossFootage;// Total square footage
float livingFootage;// Living area
float costPerFoot; // Cost/foot
of living area
// Set up floating pt.output format
cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint);
grossFootage = LENGTH * WIDTH * STORIES;
livingFootage =
grossFootage - NON_LIVING_SPACE; costPerFoot
= PRICE /
livingFootage; cout
<< "Cost per square foot is " <<setw(6)
<< setprecision(2)<<costPerFoot
<< endl; return 0;
}
-
Same program with good formatting:
//********************************************************
// HouseCost program
// This program computes the cost per square foot
of
// living space for a house, given the dimensions
of
// the house, the number of stories, the size of
the
// nonliving space, and the total cost less land
//********************************************************
#include <iostream.h>
#include <iomanip.h> // For
setw() and setprecision()
const float WIDTH = 30.0;
// Width of the house
const float LENGTH = 40.0;
// Length of the house
const float STORIES = 2.5;
// Number of full stories
const float NON_LIVING_SPACE = 825.0;// Garage,closets,etc.
const float PRICE = 150000.0; //
Selling price less land
// ------------------------------------------------
main
int main()
{
float grossFootage;
// Total square footage
float livingFootage;
// Living area
float costPerFoot;
// Cost/foot of living area
// Set up floating pt.output format
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
grossFootage = LENGTH * WIDTH *
STORIES;
livingFootage = grossFootage -
NON_LIVING_SPACE;
costPerFoot = PRICE / livingFootage;
cout << "Cost per square
foot is "
<< setw(6) << setprecision(2) << costPerFoot
<< endl;
return 0;
}
-
C++ Program Formatting Guidelines:
-
Start every file with a comments section that identifies
the file and briefly describes what it does.
-
Use comments to mark the beginning of each function.
-
Use blank lines before and after functions.
-
Make sure beginning and ending braces {
and } are vertically aligned.
-
Label each variable with a comment that describes its purpose.
-
Use blank lines to set off lines of code that go together.
-
Use comments to explain anything that might not be clear.
-
Use meaningful names.
-
Begin variables with a lower case letter and use upper case
letters to begin each subsequent word.
-
Use all caps to name constants. Use underscores _
to separate words.
-
Begin user-defined function names with a capital letter.
Updated February 8, 1999 by Tom Irby.
Copyright 1999 by Thomas C. Irby.