Week2 Lecture Summary for CSC 309
These notes are not intended to be complete. They serve as an outline to the class and as a supplement to the text.
Reference Variables
- An alias for another variable
- To create a reference variable we use the reference operator
&
- A reference variable must be initialized using another variable when created.
- Any time you modify or use the reference you modify or use the data contained in the original variable
Example 1
int count = 67; int& refCount = count; // creating and initializing a reference variable
Example 2
int count = 67; int refCount = count;
Note the difference(huge) between example 1 and example 2.
In Example 1, the memory location (box) that contains the value 67 has two names, count
and refCount
. We can use refCount to read or modify the value stored in the box at that location.
In Example 2, their are two different memory locations(2 boxes) with the value 67.
Example 3
int x; int& y = x; x = 100; cout << y << endl; // output 100 ++y; cout << x << endl; // output 101
Functions
- A named piece of code that can receive values, execute statements and return a value.
- C++ functions can be global (also called top-level) or methods (also called member functions) , functions defined in a class.
- Before a function can be invoked (called) it must be declared .
Example
#include .... using namespace std; // function declaration or prototype int pow(int base, int exponent); int main(){ pow(2,7); : } // function definition int pow(int base, int exponent){ : : return .. }
- The built-in functions that come with your environment have already been declared, just
#include
the appropriate header file. - The declaration ends with a semicolon.
- The parameter names (base and exponent) in the declaration are optional and should be included for documentation.
- The parameter names (base and exponent) in the definition are required.
- The return type, function name and the parameter list data types, must be the same in declaration and definition.
- If a function does not return a value, then void is used.
Variable Scope
- A block is a section of code bounded by braces { }.
- A local Variable is defined in a functions bounding braces.
- A local variable is only available within the function it is defined.
- Function parameters are local variables.
Example
void getIncome(){ double income; cin >> income; return; } double computeTax(){ return income * .30; }
- Function
computeTax
is in violation. Variable income is only accessible ingetIncome
- When
getIncome
returns, the variableincome
disappears. - A global variable is defined outside of any block.
- Global variables are accessible from the point of definition to the end of the source code file.
- Global variables should be used sparingly and with constants.
Example
double income; double computeTax(){ return income * .30; } void getIncome(){ cin >> income; return; }
Parameter Passing
- Parameters to methods can be passed by value or by reference.
- When you pass by value a copy is passed and stored into the parameter.
- When you pass by reference the functions parameter becomes an alias
- Pass by reference is used to pass aggregate objects, for efficiency (you avoid making a copy) or when you want the function to change a local variable.
- See swap.cpp
Function Overloading
- Two or more functions with the same name
- The parameter lists of the function must be different. Either by the number of parameters or the data type of the parameters or both
Example1
The max function is overloaded, therefore this code will compile.
int max(int first, int second); int max(double first, double second); int max(double first, double second, double third);
Example2
The max function is NOT overloaded, therefore this code will NOT compile.
int max(int first, int second); int max(int second, int first); int max(int f, int s);
Default Parameters
See linebreak.cpp
Monthly Payment
Write a program to compute the monthly payment on a loan using the formula.
In the formula P is the amount borrowed, i is the monthly rate and n is the number of payments.
The amount borrowed, the rate and number of years will be gotten form the user.
We will break the program up using the following functions.
void getInput(double& principal, double& rate, int& years); double computePayment(double principal, double rate, int years); void showMonthlyPayment(double principal,double rate, int years);
Statistics Program
Uses functions to compute the mean and median of values stored in a vector. Here are the function prototypes.
double median(vector<double> temperatures); double mean(const vector<double>& temperatures);
- When the
median
function is called the argument will be passed-by-value. Since in this case the argument is an object (vector) the original vector object is cloned. When the median performs the sort operation it does it on the clone not the original vector. Therefore the sequence of values in the original vector remains the same. - The parameter to the
mean
function is a reference to the original vector. Since mean should not modify the vector we use the keyword const in the parameter. - Whenever an object is passed by reference and the calling function should not change the state of the object, you should always use
const
.
Iterators
- Are objects that point to other objects.
- Provide an interface between containers and algorithms. Let
vec
be avector
sort(vec.begin(), vec.end())
begin
returns an iterator to the first element in the vectorend
returns an iterator to one past the last element of the vector.vector
vector<int>::iterator it;
it
whose type is iterator
.
iterator
is defined in the class vector<int>. ::
is called the scope operator.
Example
vector<int> vec; vec.push_back(4); vec.push_back(6); vec.push_back(10); vector<int>::iterator it = vec.begin(); // point to the first element in the vector. cout << *it << endl; // output 4 cout << *it << endl; // output 4 again ++it; // advance it to the next element. cout << *it << endl; // output 6 // can loop through for(it = vec.begin(); it != vec.end(); ++it) cout << *it << endl;
*
is called the dereference operator. Allows access to the value that the iterator is pointing
at.Problem
Add a function that returns the smallest element in the vector. Use an iterator to traverse the vector. The declaration of the method is.
double min(const vector<double>& temperatures);
For efficiency we want to pass by reference. Since the min function does not need to change the values stored in the vector, we use const
. That is, we will pass a reference to a constant vector.
When using iterators for read only we need to use a const_iterator
.
vector<int>::const_iterator it;