## CS 1711 Lab - November 3 and 5, 1998 Counting, cases, and streams

### Exercise: Switching off-by-one

A common error of loops, but less common for counted loops is the `off-by-one'. You are going to look at a program's behaviour, predict the off-by-one error in a while statement and fix it with a counted loop. A switch statement also shows up.
1. Obtain the file swby1.cpp from the usual directory. Compile it and run it with input values of 1, 2, 3.
2. What is wrong in the output?
3. Modify the program so that it behaves correctly. Store the result as swby2.cpp to show to your instructor.
4. Now modify swby1.cpp leaving the loop fixed, but changing the switch statement so that the program behaves correctly. Store the result as swby3.cpp to show to your instructor.

### Stream I/O

In this exercise we are going to implement a monthly cheque-book writing program. The program input is a sequence of transaction records on the file trans.dat. The output is to be written to the file cheque.out which you should store on your M:-drive. An outline of the program is in cheque.cpp. The first line of the data file is an integer code for the month, a number of tranactions and an initial balance, for example 10 7 510.77 means the month is October, there are 7 transactions from an initial balance of \$510.77. Each line following consists of a `D' or `C' (for debit or credit), an integer (for the date), and a real value (for the amount). The file cheque.out should look like (in part, for example):

```October
Date Type Amount Balance
1                \$510.77
3     C   25.00   535.77
6     D   100.00  435.77
...  ...   ...     ...
Final balance    \$455.44
```

where the last line simply gives the final monthly balance.

The steps are as follows:

1. Obtain the file trans.dat, store it on your M: drive.
2. Obtain the outline file cheque.cpp.
3. Carefully read the function prototypes.
4. Add any necessary file directives.
5. Add suitable stub functions after the main function.
6. Save your version with stubs as cheqstub.cpp.
7. Write the required functions one at a time to replace the stub functions. Test each function after you have written it.
8. Save your program as cheque.cpp. Demonstrate your version with stubs and the finished program (you should begin by showing the instructor your M:-drive without a cheque.out file, then run the program...)