EECS168 09:Lab14
| Navigation | 
|---|
| Home | 
| Information | 
| Classwork | 
More on Classes and Intro to Recursion
Constructors of classes
You often want to initialize some or all the member variables for an object when you declare the object. C++ includes special provisions for such initializations, known as constructor. A constructor is a member function that is automatically called when an object of that class is declared. Following is an example of class with constructors:
//Program to demonstrate the class BankAccount.
#include <iostream>
#include <cstdlib>
using namespace std;
//Class for a bank account:
class BankAccount
{
public:
    BankAccount(int dollars, int cents, double rate);
    //Initializes the account balance to $dollars.cents and
    //initializes the interest rate to rate percent.
    BankAccount(int dollars, double rate);
    //Initializes the account balance to $dollars.00 and
    //initializes the interest rate to rate percent.
    BankAccount( );
    //Initializes the account balance to $0.00 and the interest rate to 0.0%.
    void update( );
    //Postcondition: One year of simple interest has been added to the account
    //balance.
    double get_balance( );
    //Returns the current account balance.
    double get_rate( );
    //Returns the current account interest rate as a percentage.
    void output(ostream& outs);
    //Precondition: If outs is a file output stream, then
    //outs has already been connected to a file.
    //Postcondition: Account balance and interest rate have been written to the
    //stream outs.
private:
    double balance;
    double interest_rate;
    double fraction(double percent);
    //Converts a percentage to a fraction. For example, fraction(50.3)
    //returns 0.503.
};
int main( )
{
    BankAccount account1(100, 2.3), account2;
    cout << "account1 initialized as follows:\n";
    account1.output(cout);
    cout << "account2 initialized as follows:\n";
    account2.output(cout);
    account1 = BankAccount(999, 99, 5.5);
    cout << "account1 reset to the following:\n";
    account1.output(cout);
    return 0;
}
BankAccount::BankAccount(int dollars, int cents, double rate)
{
    if ((dollars < 0) || (cents < 0) || (rate < 0))
    {
        cout << "Illegal values for money or interest rate.\n";
        exit(1);
    }
    balance = dollars + 0.01*cents;
    interest_rate = rate;
}
BankAccount::BankAccount(int dollars, double rate)
{
    if ((dollars < 0) || (rate < 0))
    {
        cout << "Illegal values for money or interest rate.\n";
        exit(1);
    }
    balance = dollars;
    interest_rate = rate;
}
BankAccount::BankAccount( ) : balance(0), interest_rate(0.0)
{
   //Body intentionally empty
}
void BankAccount::output(ostream& outs)
{
    outs.setf(ios::fixed);
    outs.setf(ios::showpoint);
    outs.precision(2);
    outs << "Account balance $" << balance << endl;
    outs << "Interest rate "<< interest_rate << '%' << endl;
}
Program counter.cpp
Define a class for a type called CounterType. An object of this type is used to count things, so it records a count that is a nonnegative whole number.
Requirements
- Include a default constructor that sets the counter to zero.
 - Include a constructor with one argument that sets the counter to the value specified by its argument. Be sure that this constructor does not allow the value of the counter to become negative.
 - Include a member function to increase the count by one.
 - Include a member function to decrease the count by one. Be sure that this function does not allow the value of the counter to become negative.
 - Include a member function that returns the current count value.
 - Include a member function that outputs the count to a stream. This function has one formal parameter of type ostream.
 - Write a main program to test the class. Each function should be tested at least once. Following is an example of the output to the screen:
 
counter1 initialized as follows:
Current value of the counter is: 2
counter2 initialized as follows:
Current value of the counter is: 0
counter1 is increased by one.
Current value of the counter is: 3
counter1 is decreased by one.
Current value of the counter is: 2
Attempt to decrease counter2.
Illegal values for counter.
Recursive Functions
An alternative to using nested loops for some types of computations is to use recursive functions. Generally if you are having trouble determining how many levels of nested loops a particular problem requires, you may find it easier to write a recursive function instead. The assignments in this lab will be fairly simple ones, so you may immediately recognize how to do them using a while or for loop, but the objective is to get you thinking recursively in preparation for Homework 8 on classes and recursion.
Similarly to for and while loops, recursive functions have an initial condition and a terminating condition. Choosing and improper terminating condition can cause an infinite recursive cycle, just like you can have an infinite loop in you code.
Here is a basic example of alternative ways to get the same outcome using loops and a recursive function:
// Using a for loop
for (i=0;i<10;i++){
    cout << i << ' ';
}
cout << endl;
// Using a while loop
i=0;
while (i<10){
    cout << i << ' ';
    i++;
}
cout << endl;
// Using a recursive function
void recursive(int i)
{
    if (i<10){                 // Terminating condition, because recursive is not called again if condition not met.
        cout << i << ' ';
        recursive(i+1);
    }
}
int main()
{
    recursive(0);
    cout << endl;
    return 0;
}
In each case the output is:
1 2 3 4 5 6 7 8 9
Recursive functions are not necessarily void functions. Here is an example of a recursive function to calculate the factorial of an integer:
#include<iostream>
using namespace std;
int factorial(int number)
{
    if(number>1){
        number = number * factorial(number-1);
        return number;
    }else{
        return 1;
    }
}
int main()
{
    cout << factorial(10) << endl;
    return 0;
}
Copy the factorial example into a file called recursion.cpp, and modify it to emulate the pow(x,y) function you have used previously, but do so recursively. Call the new function power(x,y) where x is the integer base and y is the integer exponent x is raised to. The function should return the integer result after calling itself recursively.
Lab Submission
- counter.cpp
 - recursion.cpp
 
The submission procedure is the same as was described in previous labs, except that:
- Your tarball and the directory inside it should be named like Smith-1234567-Lab-14
 - The email subject should be "[EECS 168] Lab 14" (without the quotes).
 
Remember to include your full name, student number, and disk usage in the email.