Solutions to Midterm
30
The program computes the sum of the even integers between 0 and 10, inclusive. The result is ouput to the terminal
11
while (i < 10) {
What effect would this have on the program?
The program would output 20 instead of 30 [since 10 would not be added.]
while (i >= 10) {
What effect would this have on the program?
The program would output 0 [since the loop would fail immediately].
i++;(and line 11 is in its original form "while (i <= 10)"). What effect would this have on the program?
No change [since i++ is equivalent to i = i + 1].
The program would go into an infinite loop [since i would be stuck at 0].
#include <fstream.h>
#include <iomanip.h>
#include <iostream.h>
int main() {
float balance; // Initial and ending balance
float check_amount; // Amount of each check
int num_checks = 0; // Number of checks read
ifstream file; // Input file
//
// Set up floating point output format. (NOT REQUIRED in student answer.)
//
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
//
// Prompt for and read the initial balance.
//
cout << "Input the initial balance: ";
cin >> balance;
//
// Open checks file and read the first check amount.
//
file.open("checks");
file >> check_amount;
//
// Process the remaining checks in the file, decrementing the balance and
// incrementing the check counter as each is read.
//
while (file) {
balance = balance - check_amount;
num_checks = num_checks + 1;
file >> check_amount;
}
//
// Output the results.
//
cout << num_checks << " checks read. "
<< "Final balance is "
<< setprecision(2) << balance
<< endl;
}