Exercises in this lecture   previous -- Keyboard shortcut: 'p'        Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home      

Exercise 4.6
Pyramid BankAccounts


This exercise can be seen as a continuation of the bank account exercise in which we supplied a bank account with a backup account. The primary purpose of the exercises is to train recursive object-oriented programming.

We organize bank accounts in a tree structure (called a pyramid) in which each bank account may have two sons which are also bank accounts. The money in the account are somehow distributed on the accounts of the pyramid.

Program a version of class BankAccount with an owner, a balance, and possible references to two additional bank accounts: leftAccount and rightAccount. A skeleton of this class is provided together with a client program. You can assume that an account is either a leaf or the account has two sons.

  • Program the Balance method. It should add together the contributions from all accounts in the pyramid.
  • Program the method Deposit. The message ba.Deposit(amount) inserts one third of the amount in the receiver, one third in the left part of the pyramid (recursively), and one third in the right part of the pyramid (recursively). In case of a leaf account, ordinary simple depositing is used.
  • Program the method Withdraw. The message ba.Withdraw(amount) withdraws recursively half of the amount from the left part of the pyramid and recursively half of the amount from the right part of the pyramid. In case of a leaf account, ordinary simple withdrawing is used.
  • Program a method DistributeEven which distributes the total amount of money evenly on all accounts in the pyramid.


Solution