Nested loops in C++ and user input - c++

Pretty new here to programming, and I have an assignment where I need to achieve the following:
ask for total amount of people
get each of their names
allow user to enter up to 5 scores for each person
if there are less than 5 scores for a given person, inputting -100 will stop it
So far I have written this:
#include <iostream>
using namespace std;
int main() {
string personName;
int totalPerson, personScoreCounter;
double personGrade, personGradeTotal;
cout << "Input total amount of people: ";
cin >> totalPerson;
for (int person = 1; person <= totalPerson; person++)
{
cout << "Input name for person " << person << ": ";
getline(cin, personName);
cin.ignore();
while ( (personGrade != -100) && (personScoreCounter <= 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
if (personGrade >= 0 && personGrade <= 100) // valid range of scores
{
personGradeTotal += personGrade;
personScoreCounter++;
}
else
{
cout << "Input only scores from 0-100" << endl;
}
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
}
}
// calculate averages and other stuff in here.
return 0;
}
After getting their name, only the last cout inside the while loop seems to execute first, then it starts from the top and so on until the for loop hits the end depending on totalPerson. I know I'm missing a few things in here, probably in the order of operations and also the way I am executing my loops, but I just can't see it. Could any of you guys with experience in the language please give me any pointers as to what's happening here and how I can fix it? Thank you.

Inside your while group, you only want to use your cout line once (at the beginning looks good).
Your first check should be for ==-100 or similar, since as it is now, you'll get a "Input only scores from 0 to 100" message if you enter -100.
You should keep a cin.ignore(); call after each use of cin >> VARIABLE, since then you will drop the EoL character.
Example code:
#include <iostream>
using namespace std;
int main() {
int totalPerson;
cout << "Input total number of people: ";
cin >> totalPerson;
cin.ignore();
for (int person = 1; person <= totalPerson; person++)
{
int personScoreCounter=0;
double personGrade = -1, personGradeTotal=0;
string personName;
cout << "Input name for person " << person << ": ";
std::getline(cin, personName);
while ( (personGrade != -100) && (personScoreCounter < 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
cin.ignore();
if (personGrade == -100) {
break;
} else if (personGrade >= 0 && personGrade <= 100) {
personGradeTotal += personGrade;
personScoreCounter++;
} else {
cout << "Input only scores from 0-100" << endl;
}
}
// calculate averages and other stuff in here.
double avg = personGradeTotal / personScoreCounter;
cout << "Avg = " << avg << endl;
}
return 0;
}
Some of your variables also needed to move inside the for loop.
Additionally I changed the limits on the personScoreCounter to [0:4] rather than [1:5] - this way you can use it for averaging more easily.

You might also try cin.getline() instead of getline(std::cin , ... ):
int max_length = 30;
std::cin.getline(personName, max_length, '\n'); // \n is option termination.
This allows whitespaces in the input also.
http://www.cplusplus.com/reference/istream/istream/getline/

Related

When using vector and arrary for multiple customer data it does not calculate correctly

When I run the program with either one or more customers. It seems to be that Only with the first customer data, the code I have does not do the calculations correctly for the first customer when trying to get the monthly payments and interest but the calculations are done correctly for the rest of the customers data inputted. What am I missing? Thank you.
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
//Variables
vector <double> Loanlgth, Loanamt, interestRate;
vector <double> monthlyPay(100), loanTotal(100), creditScore(100), totalInterest;
char yes;
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
vector <string> customerName;
int option;
int numCustomers = 0;
int index = 0;
//Program
cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
do
{
cout << "UA Bank menu:\n\n"
<< "1. Enter your information\n"
<< "2. See your loan requirements\n"
<< "3. Exit program\n\n"
<< "Choose an option: ";
cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
cout << "Please enter a valid menu option: ";
cin >> option;
}
if (option == 1) //Customer enters their information
{
cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
cin >> numCustomers;
for (index = 0; index < numCustomers; index++)
{
string tempName;
double tempLoanamt, tempLoanlgth, tempcreditScore, tempinterestRate, tempinterest;
cout << "Please enter your name: ";
cin >> tempName;
customerName.push_back(tempName);
cout << "Please enter the loan amount: $";
cin >> tempLoanamt;
Loanamt.push_back(tempLoanamt);
cout << "Please enter the length of the loan in months: ";
cin >> tempLoanlgth;
Loanlgth.push_back(tempLoanlgth);
cout << "What is your current credit score? ";
cin >> tempcreditScore;
creditScore.push_back(tempcreditScore);
if (tempcreditScore <= 600)
tempinterestRate = .12;
interestRate.push_back(tempinterestRate);
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
//Calculations
tempinterest = Loanamt[index] * interestRate[index];
totalInterest.push_back(tempinterest);
loanTotal[index] = (Loanamt[index] + totalInterest[index]);
monthlyPay[index] = loanTotal[index] / Loanlgth[index];
}
}
if (option == 2) // Displays monthly payment
{
cout << fixed << setprecision(2);
for (index = 0; index < numCustomers; index++)
cout << customerName[index] << " your total loan is " << loanTotal[index] << "\n"
<< "with a monthly payment of $" << monthlyPay[index] << "\n"
<< "for " << Loanlgth[index] << " months with an interest\n"
<< "rate of " << interestRate[index] << endl;
}
} while (option != EXIT_PROGRAM);
system("pause");
return 0;
}
Currently, interestRate is populated wrongly. Initially, it contains a garbage value because it is not initialized and if the first condition is not true, the garbage value is pushed, otherwise .12. Next, if the second condition is true, .05 is pushed, otherwise the values from the above flow. So, these combinations of garbage and assigned values are causing values to be pushed twice.
Here's your code:
if (tempcreditScore <= 600)
tempinterestRate = .12;
interestRate.push_back(tempinterestRate);
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
You can correct this in a number of ways:
// push after the calculation is complete
if (tempcreditScore <= 600)
tempinterestRate = .12;
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
or, with if-else (preferable):
if (tempcreditScore <= 600)
tempinterestRate = .12;
else
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
or, with ternary operator ?: (conciseness and you can make it const):
const double tempinterestRate = (tempcreditScore <= 600 ? .12 : .05);
interestRate.push_back(tempinterestRate);
Apart from this, there are a number of points:
The naming convention is inconsistent throughout the code.
The variables must be initialized because the uninitialized ones may lead to Undefined Behavior.
In the absence of an aggregate type such as struct or class and with multiple pieces of information to store separately in vectors, it is better to keep all the push_backs exactly to once per iteration.
Magic numbers can be avoided for 600, .12 and .5.
The magic numbers for option comparison in if conditions can be removed with their proper constant equivalents i.e. INPUT_CUSTOMER and DISPLAY_LOAN. And, if-else can be used instead of if-if.
The scoping could be improved by moving the variables and objects closer to where they are used.
The vertical blank spaces can improve readability for relevant code blocks.
And, Why is "using namespace std;" considered bad practice?
There might be some other points that you can observe in the following updated code (live):
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
int main()
{
// Variables
std::vector<std::string> customerNames;
std::vector<double> loanLengths, loanAmounts, interestRates;
std::vector<double> monthlyPays, loanTotals, creditScores, totalInterests;
// Program
std::cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
int option = EXIT_PROGRAM;
do
{
std::cout << "UA Bank menu:\n\n"
<< "1. Enter your information\n"
<< "2. See your loan requirements\n"
<< "3. Exit program\n\n"
<< "Choose an option: ";
std::cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
std::cout << "Please enter a valid menu option: ";
std::cin >> option;
}
if (option == INPUT_CUSTOMER) //Customer enters their information
{
int numCustomers = 0;
std::cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
std::cin >> numCustomers;
for ( int index = 0; index < numCustomers; index++ )
{
std::string name;
double loanAmount = 0.0, loanLength = 0.0, creditScore = 0.0;
std::cout << "Please enter your name: ";
std::cin >> name;
customerNames.push_back( name );
std::cout << "Please enter the loan amount: $";
std::cin >> loanAmount;
loanAmounts.push_back( loanAmount );
std::cout << "Please enter the length of the loan in months: ";
std::cin >> loanLength;
loanLengths.push_back( loanLength );
std::cout << "What is your current credit score? ";
std::cin >> creditScore;
creditScores.push_back( creditScore );
double interestRate = 0.0;
if (creditScore <= 600)
interestRate = .12;
else
interestRate = .05;
// Ternary operator (?:) may also be used here
// const double interestRate = creditScore <= 600 ? .12 : .05;
interestRates.push_back(interestRate);
//Calculations
const double tempTotalInterest = loanAmounts[index] * interestRates[index];
totalInterests.push_back( tempTotalInterest );
const double tempTotalLoan = loanAmounts[index] + totalInterests[index];
loanTotals.push_back( tempTotalLoan );
const double tempMonthlyPay = loanTotals[index] / loanLengths[index];
monthlyPays.push_back( tempMonthlyPay );
}
}
else if (option == DISPLAY_LOAN) // Displays monthly payment
{
std::cout << std::fixed << std::setprecision(2);
for (int index = 0; index < customerNames.size(); index++)
{
std::cout << "\n---\n";
std::cout << customerNames[index] << " your total loan is " << loanTotals[index]
<< "\nwith a monthly payment of $" << monthlyPays[index]
<< "\nfor " << loanLengths[index] << " months with an interest"
<< "\nrate of " << interestRates[index] << std::endl;
std::cout << "---\n";
}
}
} while (option != EXIT_PROGRAM);
return 0;
}

Call array storing string type from one while to another

How to fix the code? I can't use vectors. I need to be able to call the names for the courses from the first while to the second one and display them.
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
while (count <= nclass ) // while
{
//Information for the class
{
cout << "Please enter the course name for the class # "<< count << endl;
getline (cin, name);
string name;
string coursename[nclass];
for (int i = 0; i < nclass; i++) {
coursename[i] = name;
}
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[i] << endl;
}
return 0 ;
}
you are declaring coursename as local inside loop and then using it outside so you get a compile time error (coursename is undeclared identifier).
one question: what is the role of inner for-loop????!!!
you use a for loop inside while loop through which you are assigning all the elements the same value as the string name has!!!
so every time count increments the inner for loop assigns the new value of name after being assigned, to the all elements of coursename.
count is undefined! so declare it and initialize it to 1 or 0 and take this in mind.
you wrote to the outbounds of coursname: count <= nclss to correct it:
while(count < nclass)...
another important thing: clear the input buffer to make cin ready for the next input. with cin.ignore or sin.sync
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
string coursename[nclass];
int count = 0;
while (count < nclass ) // while
{
//Information for the class
string name;
cout << "Please enter the course name for the class # "<< count << endl;
cin.ignore(1, '\n');
getline (cin, name);
coursename[count] = name;
cin.ignore(1, '\n');
count++;
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[x] << endl;
}
This code works!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nclass = 0, count = 1, countn = 1;
string name[100];
cout << "Please enter the number of classes" << endl;
cin >> nclass;
while (count <= nclass) {
cout << "Please enter the course name for the class # " << count << endl;
cin >> name[count];
count++;
}
cout << "Here is a list of all the courses: " << endl;
while (countn <= nclass) {
cout << name[countn] << endl;
countn++;
}
return 0;
}
Note that gave the array "name" the size of 100. Nobody is going to have 100 classes! There is no need for the for loops. It is a good practice to initialize the count and the new count which is designated by countn. Why is my answer voted down when it works?

How to evaluate number greater than and less than in the same while loop?

// DiceRollProject.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int diceRoll(int max); // function definition
int getValidInteger();// function definition
int main() {
srand(time(0)); // seed the random number generator
int exitProgram = 0;
int guess, rollValue;
int maxRollValue = 6;
cout << "Hello! Let's play a dice game. Let me do the first roll for you.\n" << endl;
rollValue = diceRoll(maxRollValue);
cout << "In this roll, you got: " << rollValue << "\n" << endl;
do {
rollValue = diceRoll(maxRollValue);
cout << "What's your guess for the next roll? Enter an integer between 1 and " << maxRollValue << ": ";
guess = getValidInteger();
// TODO: Validate input
if (guess > rollValue)
{
cout << "The guess was too high!";
}
if (guess < rollValue)
{
cout << "The guess was too low!";
}
if (guess == rollValue)
{
cout << "You guessed correctly, congrats!";
}
cout << "In this roll, you got: " << rollValue << "\n" << endl;
// TODO: Evaluate result
cout << "Enter 1 to exit or any other integer to continue rolling ";
exitProgram = getValidInteger();
cout << "\n";
if (exitProgram == 1)
{
cout << "Sorry to see you go. Have a wonderful day!\n" << endl;
}
} while (exitProgram != 1);
return 0;
}
// Roll the die
int diceRoll(int max) {
int rollValue;
rollValue = (rand() % max) + 1;
return rollValue;
}
// Check if user entered an integer
int getValidInteger() {
int userInput;
cin >> userInput;
while (userInput < 1) {
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}
if (cin.fail()) {
cin.clear();
cin.ignore();
cout << "Please enter an Integer only ";
cin >> userInput;
cout << "\n";
}
return userInput;
}
I have a dice roll guessing game, I'm trying to evaluate the users input, to make sure that they can't enter a number less than 1 and greater than 6, unfortunately, with just my if statements, they can still enter these numbers, although a string is displayed that the input is not valid, I want to make a while loop that keeps asking them to enter a valid number equal or greater than 1 and equal to and less than 6, if the user keeps inputting an incorrect number, the while loop will keep asking them for a valid number, until they do enter one, which will then run the program as normally.
First of all, inside the while loop you have dead code.
while (userInput < 1) {
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}
Within the loop body, the first if is always true and the second one is always false. You should enter in a loop when the user writes an invalid input. This happens when (userInput < 1 or userInput > 6)
After the evaluation of the while's condition, you should ask the user to write input
do {
cout << "Please enter an Integer only ";
cin >> userInput;
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}while(userInput < 1 || userInput > 6);
So your condition that will keep you in the while loop is if the person guesses too high or too low. Inside the while loop I would add the updating condition or statement that you would like to repeat. So in your case, "your guess is too high" or " your guess is too low" and ask for their input again. I am not a pro but I would keep it simple by constructing 2 while loops, one for too high and one for too low just like your if statements. literally you can just change your first two if statements to while loops and adding an few extra lines of cout to ask the person to guess again and validate their input. I hope this helped.
from what I've understood you are looking for something like this:
int main (){
int my_magic_number=(rand()%6)+1,usernumber=-1;
bool state;
while (usernumber!=my_magic_number){
cin>>usernumber;
state = (usernumber<1||usernumber>6);
while (state) {
cout<<"You entered a number outside the range [1,6] please try again\n";}
cin>>usernumber;
state = (usernumber<1||usernumber>6);
}
if (usernumber!=my_magic_number) {/* do whatever you want */}
} //while loop
} // main

Trouble with an if else if statement c++

I am working on a grade book project that has 5 students that I want to read the names in for and then with an inner loop grab 4 grades for each student. Something is not working on this loop. This what I am getting:
Please enter the name for student 1: Dave
Please enter the grade number 1 for Dave: 100
Please enter the grade number 2 for Dave: 100
Please enter the grade number 3 for Dave: 100
Please enter the grade number 4 for Dave: 10
Please enter the name for student 2: James
Please enter the grade number 5 for James: 100
Please enter the name for student 3: Sam
Please enter the grade number 5 for Sam: 100
Please enter the name for student 4: Jack
Please enter the grade number 5 for Jack: 100
Please enter the name for student 5: Mike
Please enter the grade number 5 for Mike: 100
It should grab 4 grades before it jumps to the next student. I have not been able to figure this out for the last couple hours. Here is the code I have so far:
#include <iostream>
#include <string>
using namespace std;
const int STUDENTS = 5; //holds how many students we have
const int SCORES = 4;
void getNames(string names[], double student1[SCORES], double student2[SCORES],
double student3[SCORES], double student4[SCORES], double student5[SCORES], int SCORES, int STUDENTS);
int main()
{
string names[STUDENTS] = {""};
char grades[STUDENTS] = {""};
double student1[SCORES] = {0};
double student2[SCORES] = {0};
double student3[SCORES] = {0};
double student4[SCORES] = {0};
double student5[SCORES] = {0};
getNames(names, student1, student2, student3, student4, student5, SCORES, STUDENTS);
// Make sure we place the end message on a new line
cout << endl;
// The following is system dependent. It will only work on Windows
system("PAUSE");
return 0;
}
void getNames(string names[], double student1[SCORES], double student2[SCORES],
double student3[SCORES], double student4[SCORES], double student5[SCORES], int SCORES, int STUDENTS)
{
for (int i = 0; i < STUDENTS; i++)
{
cout << "Please enter the name for student " << i+1 << ": ";
cin >> names[i];
cout << endl;
if (i == 0)
{
int count1 = 0;
for (count1; count1 < SCORES; count1++)
{
cout << "Please enter the grade number " << count1+1 << " for " << names[i] <<": ";
cin >> student1[count1];
cout << endl;
}
}
else if (i == 1)
{
int count2 = 0;
for (count2; count2 < SCORES; count2++);
{
cout << "Please enter the grade number " << count2+1 << " for " << names[i] <<": ";
cin >> student2[count2];
cout << endl;
}
}
else if (i == 2)
{
int count3 = 0;
for (count3; count3 < SCORES; count3++);
{
cout << "Please enter the grade number " << count3+1 << " for " << names[i] <<": ";
cin >> student3[count3];
cout << endl;
}
}
else if (i == 3)
{
int count4 = 0;
for (count4; count4 < SCORES; count4++);
{
cout << "Please enter the grade number " << count4+1 << " for " << names[i] <<": ";
cin >> student4[count4];
cout << endl;
}
}
else
{
int count5 = 0;
for (count5; count5 < SCORES; count5++);
{
cout << "Please enter the grade number " << count5+1 << " for " << names[i] <<": ";
cin >> student5[count5];
cout << endl;
}
}
}
}
Thanks for any help on this!
There's some pretty rough stuff going on in here, but the problem is that you have a semi-colon on all your inner loops except the first one:
for (count2; count2 < SCORES; count2++);
Remove the semi-colon, and the stuff in the braces will become part of the loop.
I'm going to suggest you make your code a little tidier and less error-prone by chucking all those function arguments into their own array when you enter the function, like this:
double *scores[5] = { student1, student2, student3, student4, student5 };
Then you take OUT all that repetition - the copy/paste is what caused your problems to begin with:
for (int i = 0; i < STUDENTS; i++)
{
cout << "Please enter the name for student " << i+1 << ": ";
cin >> names[i];
cout << endl;
for (int s = 0; s < SCORES; s++)
{
cout << "Please enter the grade number " << s+1 << " for " << names[i] <<": ";
cin >> scores[i][s];
cout << endl;
}
}
Why can't you use two nested loops like
for (int studix=0, stduix<STUDENTS; studix++) {
//...
for (int gradix=0; gradix<SCORE; gradix++) {
//...
}
//....
}
BTW, the condition could be a more complex one, e.g. with the internal loop being
bool goodgrade=true;
for (int gradix=0; goodgrade && gradix<SCORE; gradix++) {
// you could modify goodgrade or use break; inside the loop
}
Don't forget the possible use of continue and break inside a loop.
And please, take time to read some good C++ programming book
Building on Basile's answer and my comments:
int main()
{
string names[STUDENTS] = {""};
char grades[STUDENTS] = {""};
double student1[SCORES] = {0};
double student2[SCORES] = {0};
double student3[SCORES] = {0};
double student4[SCORES] = {0};
double student5[SCORES] = {0};
double *gradeArray[STUDENTS];
gradeArray[0] = student1;
gradeArray[1] = student2;
gradeArray[2] = student3;
gradeArray[3] = student4;
gradeArray[4] = student5;
for (int studix=0, stduix<STUDENTS; studix++) {
// get the name of the student
for (int gradix=0; gradix<SCORE; gradix++) {
// put the grades in gradeArray[studix][gradix]...
}
//....
}
Yes, I know about 2 D arrays, but I am trying to make explicit how this can be done with "five individual arrays". Clumsy, but I believe this works.

Functions and structures in C++

/*I got stumped within my code. I think classes will be simpler than structures, but the chapter within my book makes me do structures. : / I am currently getting an error message that my function was not matched up for an overloaded function. The book does talk about them, but the examples of overloading functions in the book aren't helping me out. Also the book wants me to enter account numbers and fill in the objects and when they are asked for an account number they should have the opportunity to "QUIT" entering numbers and proceed onto the next part of the program; that whole way of thinking has my brain a bit fried and I was hoping I could get some help. I apologize if the formatting of my code is messy, I tried to reformat it within here so it would all go into the code brackets.
The Error happens at line... 161 at the displayAccounts function. Parameters were different within the top and bottom of the two functions I changed it and it works. I am going to go over different parts and if its correct post the correct code.*/
I figured out exactly the question that I need. I need the "QUIT" loop to be allowed to be followed up within the account numbers. This would allow the user to enter in a 0 at any time when asked to enter an account number and this was what was confusing me the most.
#include <iostream>
#include <iomanip>
using namespace std;
struct BankAccount
{
void enterAccountsData(BankAccount *accounts);
void computeInterest(BankAccount *accounts);
void displayAccounts(BankAccount *accounts, const int QUIT);
int accountNum; // holds the account number.
double accountBal; // holds the account balance.
double annualInterest; // holds the interest rate.
int term; // holds the term for the accounts.
};
int main()
{
const int MAX_ACCOUNTS = 100; // The maximum number of bank accounts.
const int QUIT = 0; // sentinal value.
int input;
int num = 0;
BankAccount data[MAX_ACCOUNTS];
BankAccount display;
cout << "Enter " << QUIT << " to stop, otherwise enter 1 and procreed.";
cin >> input;
while(true)
{
if(input != QUIT)
{
data[MAX_ACCOUNTS].enterAccountsData(data);
data[MAX_ACCOUNTS].computeInterest(data);
}
else
{
break;
}
}
display.displayAccounts(data, QUIT);
//system("pause");
return 0;
}
void BankAccount::enterAccountsData(BankAccount *accounts)
{
cout << setprecision(2) << fixed;
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts. (change the number for more bank accounts)
int found;
int quit = 0;
/* First for loop which asks and holds the account information
entered in by the user. */
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
do
{
found = 0;
cout << "Enter in account # " << (num + 1) << endl;
cin >> accounts[num].accountNum; // holds the value of the account number
// Checks if the account number is valid.
while(accounts[num].accountNum < 999 || accounts[num].accountNum > 10000)
{
cout << "Account number must be four didgets:" << endl;
cin >> accounts[num].accountNum;
}
// Checks if the account numbers are the same.
for(int check = 0; check < num; check++)
{
while(accounts[num].accountNum == accounts[check].accountNum)
{
cout << endl << "Account Numbers cannot be the same, enter in a new account number." << endl;
found = 1;
break;
}
}
} while(found); // end of do while.
// Holds the values for the account balances.
cout << "Enter the accounts balance." << endl;
cin >> accounts[num].accountBal;
// Makes sure that the account balance is not negative.
while(accounts[num].accountBal < 0)
{
cout << "Account cannot have a negitive balance." << endl;
cin >> accounts[num].accountBal;
}
// Holds the interest rate.
cout << endl << "Enter the interest rate for account # " << (num + 1) << endl;
cin >> accounts[num].annualInterest;
// Makes sure the interest rate is valid
while(accounts[num].annualInterest > 0 && accounts[num].annualInterest > 0.15)
{
cout << endl << "Annual interest must be from 0 to 0.15." << endl;
cin >> accounts[num].annualInterest;
}
// Makes sure the interest rate is not negetive
while(accounts[num].annualInterest < 0)
{
cout << endl << "Interest rate cannot be negetive" << endl;
cin >> accounts[num].annualInterest;
}
// Holds the value for the length of the interest.
cout << endl << "How many years will this interest rate be held for? " << endl;
cin >> accounts[num].term;
//Checks for valid length of time for the term held
while(accounts[num].term < 0 || accounts[num].term > 11)
{
cout << "The Term must be greater than 1 and should not exceed 10" << endl;
cin >> accounts[num].term;
}
}
cout << "If you wish to stop enter 0 otherwise type 1 to proceed" << endl;
cin >> quit;
if(quit = 0)
{
return;
}
}
void BankAccount :: computeInterest(BankAccount *accounts)
{
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts.
const int MONTHS_IN_YEAR = 12;
double total = 0;
double average = 0;
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
/*Goes through the term year and calculates the total
of each account balance. Then calculates the average. */
for(int year = 0; year < accounts[num].term; year++)
{
for(int month = 0; month < MONTHS_IN_YEAR; month++)
{
accounts[num].accountBal = (accounts[num].accountBal * accounts[num].annualInterest) + accounts[num].accountBal;
}
int month = 1;
cout << endl << "Total amount for account # " << (num + 1) << " is: " << accounts[num].accountBal << endl ;
total += accounts[num].accountBal;
cout << endl << "The total amount of all accounts is: " << total << endl;
}
}
average = total / NUM_OF_ACCOUNTS;
cout << "Average of all the bank accounts is: " << average << endl;
}
void BankAccount :: displayAccounts(BankAccount *accounts)
{
int input = 0;
int found;
const int MAX_ACCOUNTS = 100;
int quit = 0;
cout << endl << "Which account do you want to access?" << endl <<
"To stop or look at none of the account numbers type: " << quit << endl;
cin >> input;
for(int num = 0; num < MAX_ACCOUNTS; num++)
{
while(num < MAX_ACCOUNTS && input != accounts[num].accountNum)
{
num++;
}
if(input == accounts[num].accountNum) // This if sees if an account matches what the user entered.
{
cout << "Account: " << accounts[num].accountNum << endl << "Balance is: " <<
accounts[num].accountBal << endl << "Interest rate is: " << accounts[num].annualInterest;
cout << endl << "Enter another account number or type 0 to quit." << endl;
found = 1;
cout << endl;
cin >> input;
}
if(found == 0)
{
cout << "Sorry that account doesn't exist. Enter another account number." << endl;
cin >> input;
}
}
}
In C++, classes and structs are exactly the same constructs. They are, in fact, one thing — a User-Defined Type.
There is a different that is invoked depending on whether you used the keyword struct or class to define your UDT, and that is that class-key defaults to private member access and private inheritance, whereas struct-key defaults to both being public.
Other than this syntax difference, you can use either without worrying about one being "simpler" than the other.
Anyway, your compiler error (please provide it next time) is probably due to a declaration/definition mismatch.
Your declaration:
void displayAccounts(BankAccount *accounts, const int QUIT);
Start of your definition:
void BankAccount :: displayAccounts(BankAccount *accounts) {
The start of the definition should be
void BankAccount::displayAccounts(BankAccount* accounts, const int QUIT) {
to match. I've also fixed your spacing to be nicer. :)
void displayAccounts(BankAccount *accounts, const int QUIT);
... looks different between declaration and definition. Second parameter is missing in the definition.
Not sure what your question is, but classes and structs in C++ are equivalent except that fields are public by default in structs, but private by default in classes.
In the struct’s displayAccounts() member declaration you have:
void displayAccounts(BankAccount *accounts, const int QUIT);
and when defining the method later:
void BankAccount :: displayAccounts(BankAccount *accounts)
You have just missed
const int QUIT
parameter for the member function definition.