PROGRAMMING EXAMPLE: Checking Account Balance

Similar documents
C++ Input/Output: Streams

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

I/O Streams and Standard I/O Devices (cont d.)

C++ Programming: From Problem Analysis to Program. Design, Fifth Edition. Chapter 1: An Overview of Computers and Programming Languages

CS2141 Software Development using C/C++ Stream I/O

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Objects and streams and files CS427: Elements of Software Engineering

Loops and Files. of do-while loop

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Week 3: File I/O and Formatting 3.7 Formatting Output

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

File I/O Christian Schumacher, Info1 D-MAVT 2013

Chapter 5: Loops and Files

C++ Programming Lecture 10 File Processing

Input and Output File (Files and Stream )

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ (Extensions to C)

BITG 1113: Files and Stream LECTURE 10

We will exclusively use streams for input and output of data. Intro Programming in C++

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

Chapter 12. Streams and File I/O

System Design and Programming II

READ THIS NOW! Failure to read and follow the instructions below may result in severe penalties. Do not start the test until instructed to do so!

Chapter 3 - Notes Input/Output

Tutorial letter 202/2/2018

Recitation: Loop Jul 7, 2008

Summary of basic C++-commands

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

What we will learn about this week:

Definition Matching (10 Points)

Expressions, Input, Output and Data Type Conversions

Chapter 3 Problem Solving and the Computer

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Chapter 3: Input/Output

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Simple File I/O.

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

BITG 1233: Introduction to C++

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Why Is Repetition Needed?

COMP322 - Introduction to C++

COMP322 - Introduction to C++

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Chapter 4 - Notes Control Structures I (Selection)

CSCE 206: Structured Programming in C++

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Setting Justification

Question 1 Consider the following structure used to keep employee records:

Lecture 3 The character, string data Types Files

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

The following is a typical execution run of this program:

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

TEST 1 CS 1410 Intro. To Computer Science Name KEY. October 13, 2010 Fall 2010

Name Section: M/W T/TH Number Definition Matching (8 Points)

Example 3. #include <iostream> using namespace std; int main()

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

CS242 COMPUTER PROGRAMMING

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

LECTURE 02 INTRODUCTION TO C++

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

1. In C++, reserved words are the same as predefined identifiers. a. True

Getting started with C++ (Part 2)

C++ Input/Output Chapter 4 Topics

Name Section: M/W T/TH Number Definition Matching (6 Points)

Problem Solving: Storyboards for User Interaction

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Introduction to Programming EC-105. Lecture 2

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

CHAPTER 3 BASIC INSTRUCTION OF C++

Programming. C++ Basics

2. It is possible for a structure variable to be a member of another structure variable.

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Lab # 02. Basic Elements of C++ _ Part1

C++ Programming: From Problem Analysis to Program Design, Third Edition

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

CS 1428 Review. CS 2308 :: Spring 2016 Molly O Neil

Transcription:

Programming Example: Checking Account Balance 1 PROGRAMMING EXAMPLE: Checking Account Balance A local bank in your town is looking for someone to write a program that calculates a customer s checking account balance at the end of each month. The data is stored in a file in the following form: 467343 23750.40 W 250.00 D 1200.00 W 75.00 I 120.74... The first line of data shows the account number followed by the account balance at the beginning of the month. Thereafter, each line has two entries: the transaction code and the transaction amount. The transaction code W or w means withdrawal; D or d means deposit; and I or i means interest paid by the bank. The program updates the balance after each transaction. During the month, if at any time the balance goes below $1000.00, a $25.00 service fee is charged. The program prints the following information: account number, balance at the beginning of the month, balance at the end of the month, interest paid by the bank, total amount of deposits, number of deposits, total amount of withdrawals, number of withdrawals, and service charge, if any. Input A file consisting of data in the above format. Output The output is of the following form: Account Number: 467343 Beginning Balance: $23750.40 Ending Balance: $24611.49 5 Interest Paid: $366.24 Amount Deposited: $2230.50 Number of Deposits: 3 Amount Withdrawn: $1735.65 Number of Withdrawals: 6 The output is to be stored in a file. PROBLEM ANALYSIS AND ALGORITHM DESIGN The first entry in the input file is the account number and the beginning balance, so the program first reads the account number and beginning balance. Thereafter, each entry in the file is of the following form: transactioncode transactionamount

2 Chapter 5: Control Structures II (Repetition) Variables To determine the account balance at the end of the month, you need to process each entry that contains the transaction code and transaction amount. Begin with the starting balance and then update the account balance after processing each entry. If the transaction code is D, d, I, ori, the transaction amount is added to the account balance. If the transaction code is W or w, the transaction amount is subtracted from the balance. Because the program also outputs the number of withdrawals and deposits, you need to keep separate counts of withdrawals and deposits. This discussion translates into the following algorithm: 1. Declare the variables. 2. Initialize the variables. 3. Get the account number and beginning balance. 4. Get the transaction code and transaction amount. 5. Analyze the transaction code and update the appropriate variables. 6. Repeat Steps 4 and 5 until there is no more data. 7. Print the result. The program outputs the account number, beginning balance, balance at the end of the month, interest paid, amount deposited, number of deposits, amount withdrawn, number of withdrawals, and service charge, if any. You need variables to store all this information. So far, you need the following variables: acctnumber //variable to store the account number beginningbalance //variable to store the beginning balance accountbalance //variable to store the account balance at the //end of the month amountdeposited //variable to store the total amount deposited numberofdeposits //variable to store the number of deposits amountwithdrawn //variable to store the total amount withdrawn numberofwithdrawals //variable to store the number of withdrawals interestpaid //variable to store the interest paid Because the program reads the data from a file and the output is stored in a file, the program needs both input and output stream variables. After the first line, the data in each line is the transaction code and the transaction amount; the program needs a variable to store this information. Whenever the account balance goes below the minimum balance, a service charge for that month is applied. After each withdrawal, you need to check the account balance. If the balance goes below the minimum after a withdrawal, a service charge is applied. You can potentially have several withdrawals in a month; once the account balance goes below the minimum, a subsequent deposit might bring the balance above the minimum, and another withdrawal might again reduce it below the minimum. However, the service charge is applied only once.

Programming Example: Checking Account Balance 3 To implement this idea, the program uses a bool variable, isservicecharged, which is initialized to false and set to true whenever the account balance goes below the minimum. Before applying a service charge, the program checks the value of the variable isservicecharged. If the account balance is less than the minimum and isservicecharged is false, a service charge is applied. The program needs the following variables: int acctnumber; double beginningbalance; double accountbalance; double amountdeposited; int numberofdeposits; double amountwithdrawn; int numberofwithdrawals; 5 double interestpaid; char transactioncode; double transactionamount; bool isservicecharged; ifstream infile; //input file stream variable ofstream outfile; //output file stream variable Named Constants PROBLEM ANALYSIS AND ALGORITHM DESIGN (CONTINUED) Because the minimum account balance and the service charge amount are fixed, the program uses two named constants to store them: const double MINIMUM_BALANCE = 1000.00; const double SERVICE_CHARGE = 25.00; Because this program is more complex than previous ones, before writing the main algorithm, the seven steps on page 2 are described more fully here. 1. Declare the variables. Declare variables as discussed previously. 2. Initialize the variables. After each deposit, the total amount deposited is updated and the number of deposits is incremented by 1. Before the first deposit, the total amount deposited is 0, and the number of deposits is 0. Therefore, the variables amountdeposited and numberofdeposits must be initialized to 0. Similarly, the variables amountwithdrawn, numberofwithdrawals, and interestpaid must be initialized to 0. Also, as discussed previously, the variable isservicecharged is initialized to false. Of course, you can initialize these variables when you declare them. Before the first deposit, withdrawal, or interest paid, the account balance is the same as the beginning balance. Therefore, after reading

4 Chapter 5: Control Structures II (Repetition) the beginning balance in the variable beginningbalance from the file, you need to initialize the variable accountbalance to the value of the variable beginningbalance. Because the data will be read from a file, you need to open the input file. If the input file does not exist, output an appropriate message and terminate the program. Because the output will be stored in a file, you need to open the output file. Suppose the input data is in the file Ch5_money.txt. Also suppose that the output will be stored in the file Ch5_money.out. The following code opens the files: infile.open("ch5_money.txt"); //open the input file if (!infile) cout << "Cannot open the input file." << endl; cout << "Program terminates!!!" << endl; return 1; } outfile.open("ch5_money.out"); //open the output file 3. Get the account number and starting balance. This is accomplished by the following input statement: infile >> acctnumber >> beginningbalance; 4. Get the transaction code and transaction amount. This is accomplished by the following input statement: infile >> transactioncode >> transactionamount; 5. Analyze the transaction code and update the appropriate variables: If the transactioncode is 'D' or 'd', update accountbalance by adding transactionamount, update amountdeposited by adding transactionamount, and increment numberofdeposits. If the transactioncode is 'I' or 'i', update accountbalance by adding transactionamount, and update interestpaid by adding transactionamount. If the transactioncode is 'W' or 'w', update accountbalance by subtracting transactionamount,update amountwithdrawn by adding transactionamount, increment numberofwithdrawals, and if the account balance is below the minimum and service charges have not been applied subtract the service charge from the account balance and mark the service charges ashavingbeenapplied.the following switch statement accomplishes this task.

Programming Example: Checking Account Balance 5 switch (transactioncode) case 'D': case 'd': accountbalance = accountbalance + transactionamount; amountdeposited = amountdeposited + transactionamount; numberofdeposits++; case 'I': case 'i': accountbalance = accountbalance + transactionamount; interestpaid = interestpaid + transactionamount; case 'W': case 'w': accountbalance = accountbalance - transactionamount; amountwithdrawn = amountwithdrawn + transactionamount; numberofwithdrawals++; 5 if ((accountbalance < MINIMUM_BALANCE) && (!isservicecharged)) accountbalance = accountbalance - SERVICE_CHARGE; isservicecharged = true; } Main Algorithm default: cout << "Invalid transaction code." << endl; } //end switch 6. Repeat Steps 4 and 5 until there is no more data. Because the number of entries in the input file is not known, the program needs an EOF-controlled while loop. 7. Print the result. This is accomplished by using output statements. Based on the above discussion, the main algorithm is as follows: 1. Declare and initialize the variables. 2. Open the input file. 3. If the input file does not exist, exit the program. 4. Open the output file. 5. To output floating-point numbers in a fixed decimal format with the decimal point and trailing zero, set the manipulators fixed and showpoint. To output floating-point numbers to two decimal places, set the precision to two decimal places. 6. Read accountnumber and beginningbalance. 7. Set accountbalance to beginningbalance.

6 Chapter 5: Control Structures II (Repetition) 8. Read transactioncode and transactionamount. 9. while (not end of input file) a. If transactioncode is 'D' i. Add transactionamount to accountbalance ii. Add transactionamount to amountdeposited iii. Increment numberofdeposits b. If transactioncode is 'I' i. Add transactionamount to accountbalance ii. Add transactionamount to interestpaid c. If transactioncode is 'W' i. Subtract transactionamount from accountbalance ii. Add transactionamount to amountwithdrawn iii. Increment numberofwithdrawals iv. If (accountbalance < MINIMUM_BALANCE &&!isservicecharged) 1. Subtract SERVICE_CHARGE from accountbalance 2. Set isservicecharged to true d. If transactioncode is a letter other than 'D', 'd', 'I', 'i', 'W', or 'w', output an error message. 10. Output the results. Because the data will be read from an input file, you must include the header file fstream. Because you will use the manipulator setprecision, you must also include the header file iomanip. If the input file does not exist, an appropriate message on the screen will be displayed, so the header file iostream is also included. COMPLETE PROGRAM LISTING //******************************************************* // Author: D.S. Malik // // Program - - Checking Account Balance. // This program calculates a customer's checking account // balance at the end of the month. //*******************************************************

Programming Example: Checking Account Balance 7 #include <iostream > #include <fstream > #include <iomanip > using namespace std; const double MINIMUM_BALANCE = 1000.00; const double SERVICE_CHARGE = 25.00; int main() //Declare and initialize variables //Step 1 int acctnumber; double beginningbalance; double accountbalance; 5 double amountdeposited = 0.0; int numberofdeposits = 0; double amountwithdrawn = 0.0; int numberofwithdrawals = 0; double interestpaid = 0.0; char transactioncode; double transactionamount; bool isservicecharged = false; ifstream infile; ofstream outfile; infile.open("ch5_money.txt"); //Step 2 if (!infile) //Step 3 cout << "Cannot open the input file." << endl; cout << "Program terminates!!!" << endl; return 1; } outfile.open("ch5_money.out"); //Step 4 outfile << fixed << showpoint; //Step 5 outfile << setprecision(2); //Step 5 cout << "Processing data" << endl; infile >> acctnumber >> beginningbalance; //Step 6 accountbalance = beginningbalance; //Step 7 infile >> transactioncode >> transactionamount; //Step 8

8 Chapter 5: Control Structures II (Repetition) while (infile) //Step 9 switch (transactioncode) case 'D': //Step 9.a case 'd': accountbalance = accountbalance + transactionamount; amountdeposited = amountdeposited + transactionamount; numberofdeposits++; case 'I': //Step 9.b case 'i': accountbalance = accountbalance + transactionamount; interestpaid = interestpaid + transactionamount; case 'W': //Step 9.c case 'w': accountbalance = accountbalance - transactionamount; amountwithdrawn = amountwithdrawn + transactionamount; numberofwithdrawals++; if ((accountbalance < MINIMUM_BALANCE) && (!isservicecharged)) accountbalance = accountbalance - SERVICE_CHARGE; isservicecharged = true; } default: cout << "Invalid transaction code" << endl; } //end switch infile >> }//end while transactioncode >> transactionamount; //Output Results //Step 10 outfile << "Account Number: " << acctnumber << endl; outfile << "Beginning Balance: $" << beginningbalance << endl; outfile << "Ending Balance: $" << accountbalance << endl << endl; outfile << "Interest Paid: $" << interestpaid << endl << endl;

Programming Example: Checking Account Balance 9 outfile << "Amount Deposited: $" << amountdeposited << endl; outfile << "Number of Deposits: " << numberofdeposits << endl << endl; outfile << "Amount Withdrawn: $" << amountwithdrawn << endl; outfile << "Number of Withdrawals: " << numberofwithdrawals << endl << endl; } if (isservicecharged) outfile << "Service Charge: $" << SERVICE_CHARGE << endl; return 0; Sample Run: (Contents of the output file Ch5_money.out) Account Number: 467343 Beginning Balance: $23750.40 Ending Balance: $24490.75 5 Interest Paid: $245.50 Amount Deposited: $2230.50 Number of Deposits: 3 Amount Withdrawn: $1735.65 Number of Withdrawals: 6 Input File: (Ch5_money.txt) 467343 23750.40 W 250.00 D 1200.00 W 75.00 W 375.00 D 580.00 I 245.50 W 400.00 W 600.00 D 450.50 W 35.65