C++ beginners coding error - c++

Him and thank you for the help in advance. I was just doing one of my assignments for school and I stumbled upon a problem. It's a simple bill calculator that differentiates you between a premium user and a regular one and calculates your bill based on the different rates. I thought I had finished it but now I'm getting this error. Please any help will do, just want to get this all said and done with.
Debug Error!
Program : ...\ConsoleApplication12.exe
Module : ...\ConsoleApplication12.exe
Run-Time Check Failure #3 - T
#include <iostream>
#include<iomanip>
using namespace std;
int main() {
const float Regular = 10;
const float Premium = 25;
const float RRate = .2;
const float DRate = .1;
const float NRate = .05;
int account;
int Rminutes;
int Dminutes;
int Nminutes;
int totalmin;
float Dcharge;
float Ncharge;
float total;
char service;
cout << "Enter the account number\n";
cin >> account;
cout << "Enter the service code\n";
cin >> service;
switch(service)
{case'r':
case'R':
cout << "Please enter the total amount of minutes used\n";
cin >> Rminutes;
if (Rminutes > 50) {
total = (Rminutes - 50)*RRate + Regular;
}
else {
total = Regular;
}
break;
case'P':
case'p':
cout << "Please enter how many minutes were used during the day\n";
cin >> Dminutes;
cout << "Please enter how many minutes were used during the night\n";
cin >> Nminutes;
if (Dminutes > 75) {
Dcharge = (Dminutes - 75)*DRate;
}
if (Nminutes > 100) {
Ncharge = (Nminutes - 100)*NRate;
}
total = Premium + Dcharge + Ncharge;
break;
default:
cout << "Invalid service code\n";
return 1;
break;
}
totalmin = Rminutes + Dminutes + Nminutes;
cout << "Your account number is:" << account;
cout << "Your type of service is:" << service;
cout << "your total minutes used was" << totalmin;
cout << "your bill is" << total;
return 0;
}

Try to define initialization values for all your variables. This code worked on Visual Studio too:
#include <iostream>
#include<iomanip>
using namespace std;
int main() {
const float Regular = 10;
const float Premium = 25;
const float RRate = .2;
const float DRate = .1;
const float NRate = .05;
int account=0;
int Rminutes=0;
int Dminutes=0;
int Nminutes=0;
int totalmin=0;
float Dcharge=0;
float Ncharge=0;
float total=0;
char service=0;
cout << "Enter the account number\n";
cin >> account;
cout << "Enter the service code\n";
cin >> service;
switch (service)
{
case'r':
case'R':
cout << "Please enter the total amount of minutes used\n";
cin >> Rminutes;
if (Rminutes > 50) {
total = (Rminutes - 50)*RRate + Regular;
}
else {
total = Regular;
}
break;
case'P':
case'p':
cout << "Please enter how many minutes were used during the day\n";
cin >> Dminutes;
cout << "Please enter how many minutes were used during the night\n";
cin >> Nminutes;
if (Dminutes > 75) {
Dcharge = (Dminutes - 75)*DRate;
}
if (Nminutes > 100) {
Ncharge = (Nminutes - 100)*NRate;
}
total = Premium + Dcharge + Ncharge;
break;
default:
cout << "Invalid service code\n";
return 1;
break;
}
totalmin = Rminutes + Dminutes + Nminutes;
cout << "Your account number is: " << account << "\n";
cout << "Your type of service is: " << service << "\n";
cout << "your total minutes used was " << totalmin << "\n";
cout << "your bill is " << total;
system("PAUSE");
return 0;
}

Related

How to create a program that can overwrite a pre-initialized variable with user inputted data during runtime?

I was tasked to create an ATM mock program and my problem is overwriting the money and PIN variables with the information that the user will enter.
Here it is:
#include <iostream>
using namespace std;
void Check(int money) { cout << "Your current balance is: " << money << endl; }
void Deposit(int money) {
int deposit;
cout << "Please enter the amount of cash you wish to deposit.\n";
cin >> deposit;
money += deposit;
cout << "Your new balance is: " << money << endl;
}
void Withdraw(int money) {
int withdraw;
cout << "Please enter the amount of cash you wish to withdraw.\n";
cin >> withdraw;
money -= withdraw;
cout << "Your new balance is: " << money << endl;
}
void Interest(int money) {
money += money * 0.05;
cout << "Your money with interest is: " << money << endl;
}
void Penalty(int money) {
if (money < 5000) {
money -= money * 0.02;
cout << "Your penalty is: " << money << endl;
} else
cout << "Your account will not incur a penalty because you are above the "
"minimum threshold.\n";
}
void ChangePIN(int PIN) {
int p;
cout << "Enter a new PIN: ";
cin >> p;
PIN = p;
cout << "Your new PIN is: " << PIN << endl;
}
int main() {
int money = 5000, PIN = 1234, EPIN;
cout << "Enter your PIN (Default PIN is 1234): \n";
cin >> EPIN;
if (EPIN == PIN) {
int choice;
cout << "Welcome!\n"
<< "1 - Check available balance \n"
<< "2 - Deposit cash \n"
<< "3 - Withdraw cash \n"
<< "4 - Compute for the interest of your account(5%)\n"
<< "5 - Compute for the penalty of having a balance below 5000 (2%) \n"
<< "6 - Change your PIN\n"
<< "7 - Exit\n"
<< "Your choice: ";
cin >> choice;
switch (choice) {
case 7: {
break;
}
{
case 1: {
Check(money);
break;
}
case 2: {
Deposit(money);
break;
}
case 3: {
Withdraw(money);
break;
}
case 4: {
Interest(money);
break;
}
case 5: {
Penalty(money);
break;
}
case 6: {
ChangePIN(PIN);
break;
}
}
}
return 0;
}
}
As you can see I'm pretty much a beginner at this. My problem is the money and PIN have the default values of 5000 and 1234 respectively. Now, I need to make the user be able to change these values but once I use return main() they get assigned the same starting values again, What would be the best workaround for this? I thought of using some sort of accumulator for this but I'd like some advice first.
You can simply do this by using a while loop.
Run an infinite while loop and break it whenever you want to exit from the program.
Here is the code:
#include <iostream>
using namespace std;
void Check(int money) { cout << "Your current balance is: " << money << endl; }
void Deposit(int money) {
int deposit;
cout << "Please enter the amount of cash you wish to deposit.\n";
cin >> deposit;
money += deposit;
cout << "Your new balance is: " << money << endl;
}
void Withdraw(int money) {
int withdraw;
cout << "Please enter the amount of cash you wish to withdraw.\n";
cin >> withdraw;
money -= withdraw;
cout << "Your new balance is: " << money << endl;
}
void Interest(int money) {
money += money * 0.05;
cout << "Your money with interest is: " << money << endl;
}
void Penalty(int money) {
if (money < 5000) {
money -= money * 0.02;
cout << "Your penalty is: " << money << endl;
} else
cout << "Your account will not incur a penalty because you are above the "
"minimum threshold.\n";
}
int ChangePIN(int PIN) {
int p;
cout << "Enter a new PIN: ";
cin >> p;
cout << "Your new PIN is: " << PIN << endl;
return p;
}
int main() {
int money = 5000, PIN = 1234;
while(1){ // run an infinite loop
int EPIN;
cout << "Enter your PIN (Default PIN is 1234): \n";
cin >> EPIN;
if (EPIN == PIN) {
int choice;
cout << "Welcome!\n"
<< "1 - Check available balance \n"
<< "2 - Deposit cash \n"
<< "3 - Withdraw cash \n"
<< "4 - Compute for the interest of your account(5%)\n"
<< "5 - Compute for the penalty of having a balance below 5000 (2%) \n"
<< "6 - Change your PIN\n"
<< "7 - Exit\n"
<< "Your choice: ";
cin >> choice;
switch (choice) {
case 7: {
return 0; // breaking condition
}
{
case 1: {
Check(money);
break;
}
case 2: {
Deposit(money);
break;
}
case 3: {
Withdraw(money);
break;
}
case 4: {
Interest(money);
break;
}
case 5: {
Penalty(money);
break;
}
case 6: {
PIN = ChangePIN(PIN);
break;
}
}
}
}
}
return 0;
}
Does this answer your question?

How can I find the mistake I am making in my C++ code?

In the output, I keep getting -"dollars" and -"cents" instead of positives as shown in the picture.
I have used a class named savings account to set initial balance, deposit and withdraw. And I am asked to use 1 object that prompts the user for input and another that uses overload constructor to initialize dollar and cents.
// Include Section
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class SavingsAccount
{
public:
SavingsAccount();
SavingsAccount(int, int);
void setInitial(int, int);
void setDeposit(int, int);
void setWithdraw(int, int);
void output();
private:
int dollars;
int cents;
};
// Main Function
int main()
{
// object declaration
// Bank 1
SavingsAccount bank1; //has its values set during definition by the user
//Bank 2
SavingsAccount bank2(200, 50); //uses the constructor to store values into member variables
bank2.setDeposit(40, 50);
bank2.setWithdraw(100, 98);
bank2.output();
cout << "\n\n";
// Variable declaration
string repeat;
int d, c;
int choice;
// Prompt for initial balance
cout << "welcome to your savings account! Please fill in the appropriate information.\n\n";
cout << "Initial balance (dollars): ";
cin >> d;
cout << "Initial balance (cents): ";
cin >> c;
bank1.setInitial(d, c);
do
{
cout << "Pick an option: " << endl
<< "1. Deposit money" << endl
<< "2. Withdraw money" << endl;
cin >> choice;
switch (choice)
{
case 1:
cout << "Deposit amount (dollars): ";
cin >> d;
cout << "Deposit amount (cents): ";
cin >> c;
bank1.setDeposit(d, c);
break;
case 2:
cout << "Withdraw amount (dollars): ";
cin >> d;
cout << "Withdraw amount (cents): ";
cin >> c;
bank1.setWithdraw(d, c);
break;
case 3:
break;
default:
while (choice != 1 && choice != 2)
{
cout << "Invalid choice, enter 1 or 2: \n";
cin >> choice;
}
}
// Display output
bank1.output();
// Prompt for continuing
cout << "\nWould you like to keep going? (y or Y for yes)";
cin >> repeat;
}while (repeat == "y" || repeat == "Y");
cout << "End Program.\n\n";
return 0;
}
SavingsAccount::SavingsAccount()
{
dollars = 0;
cents = 0;
}
SavingsAccount::SavingsAccount(int newD, int newC)
{
dollars = newD;
cents = newC;
cout << "Your initial balance is $" << dollars << "." << cents << endl;
}
void SavingsAccount::setInitial(int initialD, int initialC)
{
while (initialC >= 100)
{
initialC = initialC - 100;
initialD++;
}
dollars = initialD;
cents = initialC;
cout << "Your initial balance is $" << dollars << "." << cents << endl;
}
void SavingsAccount::setDeposit(int depD, int depC)
{
while (depC >= 100)
{
depC = depC - 100;
depD++;
}
dollars = depD + dollars;
cents = depC + cents;
cout << "Depositing $" << depD << "." << depC << " to your account...\n";
}
void SavingsAccount::setWithdraw(int withD, int withC)
{
while (withC >= 100)
{
withC = withC - 100;
withD++;
}
if (withD > dollars)
{
cout << "Not enough money to be withdrawn.\n";
}
else
{
dollars = withD - dollars;
cents = withC - cents;
cout << "Withdrawing $" << withD << "." << withC << " from your account...\n";
}
}
void SavingsAccount::output()
{
cout << "dollars = " << dollars << " cents = " << cents << endl;
}
You ask How can I find the mistake I am making in my C++ code? (and not What is the mistake I am making in my C++ code?)
Part of the answer to your question is, and this is especially applicable to small programs when you first start learning to program, to trace the execution of your program with pencil and paper. Then, as your programs become longer and more complicated, start watching their execution with a debugger.

How to call void function from Main

In my program I am trying to call the void function from Main but I can't figure out the correct way.
Main is at the very bottom and void GetTicketType(char &Choice) is the function I need to call to cout the ticket type.
//---------------------------------------------------------------------------
// Purpose: This program simulates a ticket office for sporting events
// Author: TBA
// Date: TBA
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
using namespace std;
const char CASH = 'C';
const char CREDIT = 'D';
const char NOSEBLEED = 'N';
const char BOX_SEAT = 'B';
const char FIFTY_YARD_LINE = 'F';
const char STUDENT_SECTION = 'S';
const float NOSEBLEED_PRICE = 43.42;
const float BOX_SEAT_PRICE = 353.85;
const float FIFTY_YARD_LINE_PRICE = 94.05;
const float STUDENT_SECTION_PRICE = 19.99;
//---------------------------------------------------------------
// Function: ConfirmChoice
// Purpose: Confirms the users ticket purchase before processing payment
// Parameters: TicketType - The type of ticket selected
// Returns: true if the user confirms the selection, false otherwise
//--------------------------------------------------------------
bool ConfirmChoice(const char TicketType)
{
char Choice;
bool Confirmed;
// Print out their selection
cout << "\nYou have chosen to purchase ";
cout << fixed << setprecision(2);
switch (TicketType)
{
case NOSEBLEED:
cout << "Nosebleed ticket(s) at a price of $";
cout << NOSEBLEED_PRICE << ".\n";
break;
case BOX_SEAT:
cout << "Box Seat ticket(s) at a price of $";
cout << BOX_SEAT_PRICE << ".\n";
break;
case FIFTY_YARD_LINE:
cout << "Ticket(s) on the 50 yard line at a price of $";
cout << FIFTY_YARD_LINE_PRICE << ".\n";
break;
case STUDENT_SECTION:
cout << "Ticket(s) in the Student Section at a price of $";
cout << STUDENT_SECTION_PRICE << ".\n";
break;
}
// Confirm the selection
cout << "Do you wish to confirm your purchase? Enter Y or N: ";
cin >> Choice;
Choice = toupper(Choice);
while (Choice != 'Y' && Choice != 'N')
{
cout << "Invalid selection. Please enter either Y or N: ";
cin >> Choice;
Choice = toupper(Choice);
}
Confirmed = (Choice == 'Y');
// Check confirmation
if (Confirmed)
cout << "You have confirmed your choice.\n" << endl;
else
cout << "You not confirmed your choice.\n" << endl;
return (Confirmed);
}
//-------------------------------------------
// Function: CalculateChange
// Purpose: To output the change due
// Parameters: ChangeDue - The amount of change needed
// Returns: Nothing
//-------------------------------------------
void CalculateChange(const float ChangeDue)
{
int Change = 0;
int Dollars = 0;
int Quarters = 0;
int Dimes = 0;
int Nickels = 0;
int Pennies = 0;
// Compute change
Change = ChangeDue * 100;
Dollars = Change / 100;
Change = Change % 100;
Quarters = Change / 25;
Change = Change % 25;
Dimes = Change / 10;
Change = Change % 10;
Nickels = Change / 5;
Pennies = Change % 5;
// Print out change
cout << "Your change is \n\t";
cout << Dollars << " Dollars\n\t";
cout << Quarters << " Quarters\n\t";
cout << Dimes << " Dimes\n\t";
cout << Nickels << " Nickels\n\t";
cout << Pennies << " Pennies\n";
}
//---------------------------------------------------------------------------
// Function: CalculateCost
// Purpose: Calculate the cost of the ticket purchase(s) (num_tickets * price_per_ticket)
// Parameters: PricePerTicket - Ticket price based on the type of ticket
// Returns: The cost of purchasing the chosen number of tickets
//---------------------------------------------------------------------------
float CalculateCost(const float PricePerTicket)
{
int TicketCount;
float Cost;
cout << "How many tickets would you like? Please enter a positive integer value: ";
cin >> TicketCount;
while (TicketCount < 0)
{
cout << "Invalid entry. Please re-enter: ";
cin >> TicketCount;
}
Cost = PricePerTicket * TicketCount;
cout << "Your bill is: $" << fixed << setprecision(2) << Cost << endl;
return Cost;
}
//---------------------------------------------------------------------------
// Function: GetPaymentType
// Purpose: Ask the user how they want to pay, cash or credit
// Parameters: None
// Returns: Value is CREDIT or CASH (global character constants)
//---------------------------------------------------------------------------
char GetPaymentType()
{
char Choice;
// Print the main menu describing the ticket payment types
cout << "+-------------------------------------------------------+\n";
cout << "+ Welcome to our Ticket Office +\n";
cout << "+-------------------------------------------------------+\n";
cout << endl << endl;
// Cash or credit card (in upper case)
cout << "How would you like to pay?\n";
cout << "Enter C for cash or D for credit card: ";
cin >> Choice;
Choice = toupper(Choice);
while (Choice != CASH && Choice != CREDIT)
{
cout << "Invalid choice. Please enter C for cash or D for credit card: ";
cin >> Choice;
Choice = toupper(Choice);
}
return Choice;
}
//---------------------------------------------------------------------------
// Function: GetTicketType
// Purpose: Get the customer's choice between 4 types of tickets
// Parameters: Choice - Set to the user's choice
// Returns: Nothing
//---------------------------------------------------------------------------
void GetTicketType(char &Choice)
{
// Ask the customer what type of ticket s/he prefers to buy
cout << "\nWhat type of ticket would you like?\n";
cout << "\t" << NOSEBLEED << " for Nosebleed Section, Price = $";
cout << NOSEBLEED_PRICE << endl;
cout << "\t" << BOX_SEAT << " for Box Seats, Price = $";
cout << BOX_SEAT_PRICE << endl;
cout << "\t" << FIFTY_YARD_LINE << " for Seats on the Fifty Yard Line, Price = $";
cout << FIFTY_YARD_LINE_PRICE << endl;
cout << "\t" << STUDENT_SECTION << " for Student Section, Price = $";
cout << STUDENT_SECTION_PRICE << endl;
// Get ticket choice (in upper case)
cout << "Enter choice: ";
cin >> Choice;
Choice = toupper(Choice);
while (Choice != NOSEBLEED && Choice != BOX_SEAT &&
Choice != FIFTY_YARD_LINE && Choice != STUDENT_SECTION)
{
cout << "Invalid choice. Please re-enter: ";
cin >> Choice;
Choice = toupper(Choice);
}
}
//---------------------------------------------------------------------------
// Function: PayWithCash
// Purpose: Handles payment by cash. Asks the user for the money until
// they enter enough, then updates the ChangeDue parameter
// Parameters: Cost - The amount due for the purchase
// ChangeDue - The amount of change due to customer
// Returns: Nothing
//---------------------------------------------------------------------------
void PayWithCash(const float Cost, float &ChangeDue)
{
float CashOffered;
// Pay in cash
cout << "Please enter enough cash. Your bill is $" << Cost << ": $ ";
cin >> CashOffered;
// Check sufficiency
while (CashOffered < Cost)
{
cout << "That is not enough to pay for your purchase!\n"
<< " Please enter at least $" << Cost << ": ";
cin >> CashOffered;
}
// Calculate change
ChangeDue = CashOffered - Cost;
}
//---------------------------------------------------------------------------
// Function: PayWithCredit
// Purpose: Handles payment by credit. Basically, just prints a statement
// telling them that their card will be charged.
// Parameters: const float Cost - the amount due for the purchase
// Returns: Nothing
//---------------------------------------------------------------------------
void PayWithCredit(const float Cost)
{
cout << "Your credit card will be billed for $" << Cost << ".\n";
}
//---------------------------------------------------------------------------
// Function: main
// Purpose: This is the main program that calls functions above.
// Parameters: None
// Returns: Nothing
//---------------------------------------------------------------------------
int main()
{
// Declarations
char TChoice ; // Ticket type: Nosebleed, box seats etc..
TChoice << GetTicketType( &TChoice);
char PChoice = GetPaymentType() ; // Payment choice: cash or credit card
bool Confirmed; // Did the user confirm the selection
float Cost; // The cost of the ticket puchased
float ChangeDue; // The amount of change owed (for cash purchases)
// Print your name and UAID
// Get the choice of payment type
// Get the choice of ticket type
GetTicketType(TChoice );
{
cout << "You have chosen the " << TChoice << "tickets. " <<".\n";
}
// Confirm the selection
// If they confirm the purchase
// Call functions to figure out the price of ticket purchase(s)
// Be sure to use the named constants
// Handle the payment
// Say goodbye
// Else
// Cancel the purchase
return 0;
}
Change
TChoice << GetTicketType( &TChoice);
To Simple
GetTicketType( &TChoice);
Since TChoice << GetTicketType( &TChoice); is doing bitwise left shift operation it will expect an integer type after <<.Your function is returning nothing(void) and thus causes an error.
It looks like you're getting an error on this line:
TChoice << GetTicketType( &TChoice);
You're calling GetTicketType and expecting to use the result. Is that really what you want to do, since it's a void function?

Passing an array of objects, the count of objects and a desired term to a function

I've run into some trouble in my programming book while completing an exercise to do with BankAccounts. The question asks:
Create a main() function that declares an array of 10 BankAccount objects. After
the first BankAccount object is entered, ask the user if he or she wants to continue. Prompt the user for BankAccount values until the user wants to quit or enters 10 BankAccount objects, whichever comes first. For each BankAccount entered, display the BankAccount details. Then prompt the user for a term with a value between 1 and 40 inclusive. Continue to prompt the user until a valid value is entered. Then pass the array of BankAccount objects, the count of valid objects in the array, and the desired term to a function that calculates and displays the values of each of the BankAccounts after the given number of years at the standard interest rate.
I have to use 3 public functions to complete this task. I only start running into problems when I try to computeInterest(). If I attempt to pass the term and count to the function and set it up in 2 for loops I will only receive the numbers and balances for a single object. I guess what i'm asking is: How do I get the program to call computeInterest and run through for each BankAccount object?
At the moment my code is set so that it will compile and run perfectly well, however, the question asks for the term and count to be sent to the function while I'm only sending the term.
I'm not sure if I'm sending the array of objects to the function? Which may be whats causing the trouble. This has been grinding my brain for quite a few days now :(. Any help/pointers are greatly appreciated!
#include<iostream>
#include<string>
using namespace std;
// Declaration Section
class BankAccount
{
private:
int accNum;
double accBal;
const static double intRate;
public:
void enterAccountData(int, double);
void computeInterest(int);
void displayAccount();
};
// Implementation Section
const double BankAccount::intRate = 0.03;
void BankAccount::enterAccountData(int num, double bal)
{
const int MIN_ACC = 1000, MAX_ACC = 9999, MIN_BAL = 0,
MAX_BAL = 100000;
cout << "Enter account number: ";
cin >> num;
while (num < MIN_ACC || num > MAX_ACC)
{
cout << "ERROR: Account number must be between " << MIN_ACC <<
" - " << MAX_ACC << ".\n" << "Enter account number: ";
cin >> num;
}
cout << "Enter account balance: $";
cin >> bal;
while (bal < MIN_BAL || bal > MAX_BAL)
{
cout << "ERROR: Account balance must be positive and less than $" <<
MAX_BAL << ".\n" << "Enter account balance: $";
cin >> bal;
}
accNum = num;
accBal = bal;
}
void BankAccount::computeInterest(int YR)
{
int x;
double interest;
for (x = 0; x < YR; ++x)
{
interest = accBal * intRate;
accBal = accBal + interest;
cout << "Account# " << accNum <<
", Balance: $" << accBal << ", Interest: " <<
intRate << endl;
}
cout << endl;
}
void BankAccount::displayAccount()
{
cout<<"Account: " << accNum <<", Balance: $" << accBal <<
", Interest: " << intRate << endl << endl;
}
int main()
{
const int END = -999, MAX_ACCOUNTS = 10, CONTINUE = 1, MIN_TERM = 1,
MAX_TERM = 40;
int i, x, count = 0, num = 0, term = 0;
double bal = 0;
BankAccount accounts[MAX_ACCOUNTS];
do
{
count++;
accounts[count - 1].enterAccountData(num, bal);
accounts[count - 1].displayAccount();
cout << "Enter " << CONTINUE << " to proceed, or " << END << " to stop: ";
cin >> i;
if (i == END || count == MAX_ACCOUNTS)
{
cout << "Enter the term of the accounts (" << MIN_TERM <<
"-" << MAX_TERM << "): ";
cin >> term;
while (term < MIN_TERM || term > MAX_TERM)
{
cout << "ERROR: Term must be between " << MIN_TERM <<
" - " << MAX_TERM << " inclusive.\n" <<
"Enter term of the accounts (" << MIN_TERM <<
"-" << MAX_TERM << "): ";
cin >> term;
}
for (x = 0; x < count; ++x)
accounts[x].computeInterest(term);
}
} while (i != END && count != MAX_ACCOUNTS);
}
You are already doing it in
for (x = 0; x < count; ++x)
accounts[x].computeInterest(term);
If really necessary, you can move that particular piece of code in a separate function, one that accepts 3 parameters: the array accounts, the count and the term.
The way you have setup the BankAccount class is that each object calculates its own interest.
Since you have several such objects, you can ask each one to compute its own interest.
Hope this helps!Let me know if there are any other questions :)

Confused about an exercise in my book

I need to be able to have the objects within the array be valid or invalid/ have value or have no value.
So if the user entered only 5 accounts out of 10 possible, it would throw away the last 5 that do not have any value what so ever, so as to not ask for a computed interest for an account that doesn't exist.
How do I do this?
#include <iostream>
#include <iomanip>
using namespace std;
class BankAccount
{
private:
int accountNum;
double accountBal;
static const double annualIntRate;
public:
void enterAccountData(int, double);
void computeInterest();
void displayAccount();
};
//implementation section:
const double BankAccount::annualIntRate = 0.03;
void BankAccount::enterAccountData(int number, double balance)
{
cout << setprecision(2) << fixed;
cout << "Enter the account number " << endl;
cin >> number;
accountNum = number;
while(number < 0 || number < 1000)
{
cout << "Account numbers cannot be negative or less than 1000 " <<
"Enter a new account number: " << endl;
cin >> number;
}
cout << "Enter the account balance " << endl;
cin >> balance;
accountBal = balance;
while(balance < 0)
{
cout << "Account balances cannot be negative. " <<
"Enter a new account balance: " << endl;
cin >> balance;
}
return;
}
void BankAccount::computeInterest()
{
const int MAX_ACCOUNTS = 10;
const int MONTHS_IN_YEAR = 12;
int months;
double rate = 0;
int counter = 0;
cout << endl << "How many months will the account be held for? " << endl;
cin >> months;
counter = 0;
do
{
accountBal = accountBal * annualIntRate + accountBal;
counter++;
}while(months > counter);
cout << endl << "Account # " << accountNum << " 's balance is:$" << accountBal << endl;
}
int main()
{
const int QUIT = 0;
const int MAX_ACCOUNTS = 10;
int counter;
int input;
int number = 0;
double balance = 0;
BankAccount accounts[MAX_ACCOUNTS];
//BankAccount display;
counter = 0;
do
{
accounts[counter].enterAccountData(number, balance);
cout << " Enter " << QUIT << " to stop, or press 1 to proceed.";
cin >> input;
counter++;
}while(input != QUIT && counter != 10);
for(counter = 0; counter < MAX_ACCOUNTS; counter++)
{
accounts[counter].computeInterest();
}
system("pause");
return 0;
}
You should try tonarrow down your questions to just what you are really asking, this is a little confusing to look at.
After the first loop, have it "remember" what value for counter it managed to reach, and then in the second loop only iterate up to that, instead of up to MAX_ACCOUNTS.
And converting from months to years is just dividing by 12 no?
It seems you have skipped the chapters about Arrays. Re-read it!
ps. surely 0 < 1000 while(number < 0 || number < 1000)
void BankAccount::enterAccountData(int number, double balance). What is the need for the two arguments ? Take the input directly for the member variables. Unnecessary operations are commented. This would also do the job -
void BankAccount::enterAccountData()
{
cout << setprecision(2) << fixed;
cout << "Enter the account number " << endl;
cin >> accountNum; // Take input directly to accountNum
// accountNum = number; // No need of this assignment
while(accountNum < 0 || accountNum < 1000)
{
cout << "Account numbers cannot be negative or less than 1000 " <<
"Enter a new account number: " << endl;
cin >> accountNum;
}
cout << "Enter the account balance " << endl;
cin >> accountBal;
// accountBal = balance; // Unnecessary assignment
while(accountBal < 0)
{
cout << "Account balances cannot be negative. " <<
"Enter a new account balance: " << endl;
cin >> accountBal;
}
// return; // What is the need of this return statement? Method signature says
// it doesn't return anything.
}
When you think of declaring variables, think of whether they are necessary. Unnecessary declaring and assigning the variables make the problem looks complex and is the source of confusion. Think simple :)