Confused about an exercise in my book - c++

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 :)

Related

Output does not include all input for my array

I have this program that is barely started:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <string>
using namespace std;
class Grade
{
public:
string studentID;
int userChoice = 0;
int size = 0;
double* grades = new double[size]{0};
};
void ProgramGreeting(Grade &student);
void ProgramMenu(Grade& student);
string GetID(Grade& student);
int GetChoice(Grade& student);
void GetScores(Grade& student);
int main()
{
Grade student;
ProgramGreeting(student);
ProgramMenu(student);
}
// Specification C1 - Program Greeting function
void ProgramGreeting(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << "Welcome to the GPA Analyzer! " << endl;
cout << "By: Kate Rainey " << endl;
cout << "Assignment Due Date: September 25th, 2022 " << endl;
cout << "--------------------------------------------" << endl;
GetID(student);
cout << "For Student ID # " << student.studentID << endl;
}
void ProgramMenu(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << setw(25) << "Main Menu" << endl;
cout << "1. Add Grade " << endl;
cout << "2. Display All Grades " << endl;
cout << "3. Process All Grades " << endl;
cout << "4. Quit Program." << endl;
cout << "--------------------------------------------" << endl;
GetChoice(student);
}
string GetID(Grade &student)
{
cout << "Enter the student's ID: ";
cin >> student.studentID;
if (student.studentID.length() != 8) {
cout << "Student ID's contain 8 characters ";
GetID(student);
}
return student.studentID;
}
int GetChoice(Grade &student)
{
cout << "Enter your selection: ";
cin >> student.userChoice;
if (student.userChoice == 1) {
GetScores(student);
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 4)
{
exit(0);
}
else
{
cout << "Please enter 1, 2, 3 or 4" << endl;
GetChoice(student);
}
}
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
for (int i = 0; i < student.size; i++) {
student.grades[i] = score;
}
count++;
}
for (int i = 0; i < student.size; i++) {
cout << student.grades[i] << " ";
}
}
I am trying to make sure my array is recording all test scores, but when I output the array in my GetScore function, each element in the array is the same or equal to the last score I entered. For example, if I choose 3 for size and then enter three values of 99.2 86.4 90.1, all three elements will read 90.1.
Why is this happening?
Your Grade class is allocating an array of 0 double elements (which is undefined behavior), and then your GetScores() function does not reallocate that array after asking the user how many scores they will enter, so you are writing the input values to invalid memory (which is also undefined behavior).
Even if you were managing the array's memory correctly (ie, by using std::vector instead of new[]), GetScores() is also running a for loop that writes the user's latest input value into every element of the array, instead of just writing it to the next available element. That is why your final output displays only the last value entered in every element. You need to get rid of that for loop completely.
Try something more like this instead (there are several other problems with your code, but I'll leave those as separate exercises for you to figure out):
class Grade
{
public:
...
int size = 0;
double* grades = nullptr;
};
...
void GetScores(Grade &student)
{
int size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
if (student.size != size) {
delete[] student.grades;
student.grades = new double[size]{0};
student.size = size;
}
for(int i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
for (int i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
Alternatively:
#include <vector>
...
class Grade
{
public:
...
vector<double> grades;
};
...
void GetScores(Grade &student)
{
size_t size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
student.grades.resize(size);
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
/* alternatively:
student.grades.clear();
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades.push_back(score);
}
*/
for (size_t i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
I removed my for loop from my while loop.
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
student.grades[count] = score;
count++;
}
for (int j = 0; j < student.size; j++) {
cout << student.grades[j] << " ";
}
}

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 integer from one method to another method in c++

I am trying to make a program that can take student's information(name, Fee) from the user, then ask the user to enter raise percentage value and then calculate the new fee of all students.
For this, I need the Fee details entered in setValues() method to be called in calculateFee() method. But I can't figure it out that how can I do this.
Kindly help me with this.
class student
{
public:
int fee;
char name[20];
//member function to read details
void setValues()
{
cout << "Enter Name:";
cin >> name;
cout << "Enter Fee:";
cin >> fee;
}
// member function to calculate the new fee
void calculateFee()
{
float rFee;
cout << "Enter the Percent value for Fee Increment";
cin >> rFee;
if (rFee <= 0)
{
cout << "Please enter value greater than 0" << endl;
}
else
{
float temp;
temp = fee * rFee / 100;
rFee = fee + temp;
cout << "New Fee is" << endl;
cout << "Name" << name;
cout << "Fee" << rFee << endl;
}
}
};
int main()
{
student std[3]; //array of students object
int n, i;
n = 3;
for (i = 0; i<n; i++){
cout << "Enter details of student " << i + 1 << ":\n";
std[i].setValues();
}
for (i = 0; i < n; i++){
cout << "\nDetails of student " << i + 1 << ":\n";
std[3].calculateFee();
}
return 0;
}

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 :)

Overloading operators..getting a logical error

I am having some trouble When I run my current program. I can add any number of transactions within this account balance, but when I go past the first array value and enter information, it displays a memory location.. Whats my problem in my code then here.
for(int i = 0; i < ACCTS; ++i)
{
do
{
debitCredit = accounts[x].operator+=(accounts[x]);
cout << "Account Balance is:$" << debitCredit << endl;
cout << "Enter " << QUIT << " to stop transactions." << endl;
cin >> selection;
}while(selection != QUIT);
++x;
}
The source code for this is here:
//Alex Weir
// Case 2 Chapter 9
#include <iostream>
#include <iomanip>
using namespace std;
class BankAccount
{
friend ostream& operator<<(ostream&, const BankAccount&);
friend istream& operator>>(istream&, BankAccount&);
private:
int accountNum;
int increaseAccountNum;
double accountBal;
double annualIntRate;
double debitCredit;
public:
BankAccount();
BankAccount(int,int,double,double,double);
int operator==(const BankAccount&);
void operator<(const BankAccount&);
void operator>(const BankAccount&);
double operator+=(BankAccount);
int operator+(BankAccount);
void displayAccounts();
};
double BankAccount::operator+=(BankAccount account)
{
cout << "How much money would you like to deposit or withdraw?" << endl <<
" Enter a negative amount to withdraw." << endl;
cin >> debitCredit;
debitCredit = debitCredit + account.accountBal;
return debitCredit;
}
int BankAccount::operator+(BankAccount account)
{
int increment;
int accountNum = increment + account.accountNum;
return accountNum;
}
void BankAccount::operator>(const BankAccount& accounts)
{
if(accountBal > accounts.accountBal)
{
cout << "Account Balance is greater than another account." << endl;
}
else
{
cout << "Account Balance is less than another account." << endl;
}
}
void BankAccount::operator<(const BankAccount& accounts)
{
if(accountBal < accounts.accountBal)
{
cout << "Account Balance is less than another account." << endl;
}
else
{
cout << "Account Balance is greater than another account." << endl;
}
}
BankAccount::operator==(const BankAccount& acctNumb)
{
int isTrue = 0;
if(accountNum == acctNumb.accountNum)
isTrue = 1;
return isTrue;
}
ostream& operator << (ostream& out, const BankAccount& Accounts)
{
cout << endl;
out << "Account #" << Accounts.accountNum << endl;
out << "Account Balance:$" << Accounts.accountBal << endl;
out << "Account interest rate: " << Accounts.annualIntRate << endl;
cout << endl;
return out;
}
istream& operator >> (istream& in, BankAccount& Accounts)
{
cout << "Enter Account # " << endl;
in >> Accounts.accountNum;
cout << "Enter Account Balance: $";
in >> Accounts.accountBal;
cout << endl << "Enter Account Interest Rate: " << endl;
in >> Accounts.annualIntRate;
cout << endl;
return in;
}
BankAccount::BankAccount()
{
accountNum = 0;
accountBal = 0;
annualIntRate = 0;
increaseAccountNum = 0;
debitCredit = 0;
}
BankAccount::BankAccount(int acctNum, int increment, double acctBal, double intRate, double debCred)
{
accountNum = acctNum;
accountBal = acctBal;
annualIntRate = intRate;
increaseAccountNum = increment;
debitCredit = debCred;
}
void BankAccount::displayAccounts()
{
cout << "Account # " << accountNum << endl;
cout << "Account balance:$" << accountBal << endl;
cout << "Account Interest Rate: " << annualIntRate << endl;
cout << endl;
}
int main()
{
const int ACCTS = 5;
const int QUIT = 0;
int x, selection;
double debitCredit = 0.0;
BankAccount accounts[ACCTS];
cout << "Enter Bank account information for: " << ACCTS << " accounts." << endl;
for(x = 0; x < ACCTS; ++x)
{
accounts[x].displayAccounts();
}
for(int i = 0; i < ACCTS; ++i)
{
do
{
debitCredit = accounts[x].operator+=(accounts[x]);
cout << "Account Balance is:$" << debitCredit << endl;
cout << "Enter " << QUIT << " to stop transactions." << endl;
cin >> selection;
}while(selection != QUIT);
++x;
}
for(x = 0; x < ACCTS; ++x)
{
accounts[x].displayAccounts();
}
/*for(x = 0; x < ACCTS; ++x)
{
cout << "Entry #" << (x + 1) << endl;
cin >> accounts[x];
cout << accounts[x];
}
double transactions;
for(x = 0; x < ACCTS; ++x)
{
}*/
Okay now that I have gotten rid of x I continue to have my variable as "i" now, I go through the 5 array elements, but I want to start with array 0 then go through the loop as many times as I want to (still playing with the balance at array element 0) after I hit "stop" or 0 when given the opportunity I want to move onto the 1st array element and go through it, adding and sub tracting for as much as I feel nessacary and repeating this process until I am fine with it. re setting the array's element variable to "i" does not do this and carries over from the last array element used.
system("pause");
return 0;
}
There are several things that might be wrong here:
debitCredit = accounts[x].operator+=(accounts[x]);
Why don't you use i instead of x? Is the value of x even initialized (the code doesn't show)?
Why do you add accounts[x] to itself? In effect you are doubling its value.
Is the accounts array big enough? How is it initialized?
Update
After looking at the extra code you posted: lose the x and use i instead. You are overstepping the bounds of the accounts array.