How to count array items within a numeric range - c++

I am tasked with trying to create a histogram from a set of sample values that a user provides. I've created the part of the program that creates the array from sample value input, but now I must take a user input for the histogram. They give min value, max value, and number of bins. So, I'm assuming the number of bins specifies the size of the array for the histogram. But I'm stumped as to how I go to my other array and count how many values are in the specified range for a particular bin. I hope this makes sense. Here is my code for the program thus far:
#include <iostream>
using namespace std;
#define MAX_SAMPLES 100
#define MAX_BINS 20
#define DOUBLE_TOLERANCE 0.0000005
#define EXIT_VALUE -999
int promptUserAndGetChoice(); //function prototype for the menu
//for information describing sample set of data and functions that operated on //those data
class SamplingClass
{
private:
char charID; //the user enters an id for his sample set
int numbOfValues; // the number of good values the user enters
double sampleValues[MAX_SAMPLES]; //for the set of sample values.
//max is 100
public:
bool readFromKeyboard(); //prototype function
bool printToScreen();//protype function
SamplingClass(); //constructor
};
SamplingClass::SamplingClass() //initializing charID
{
charID = 0;
}
bool SamplingClass::readFromKeyboard()
{
int i = 0;
cout << "Enter character identifier for this sample:";
cin >> charID;
cout << "you entered " <<charID << "\n";
cout << "Enter all samples, then enter -999 to end:\n";
while (i < MAX_SAMPLES)
{
cin >> sampleValues[i];
if
(sampleValues[i] < EXIT_VALUE + DOUBLE_TOLERANCE && sampleValues[i] > EXIT_VALUE - DOUBLE_TOLERANCE)
{
break;
}//End if/else
i++;
}//End while
numbOfValues = i;
return true;
}
//this function checks whether charID is empty and then performs accordingly
bool SamplingClass::printToScreen()
{
if (numbOfValues == 0) ///either make a test for existance first or charID
{
cout << "ERROR: Can not print uninitialized sampling!\n";
return false;
}
else
{
cout << "Data stored for sampling with identifier " << charID << ":\n";
cout << "Total samples:" << numbOfValues << "\n";
cout << "Samples (5 samples per line):\n";
int i;
for(i=0; i<numbOfValues;i++)
{
cout << sampleValues[i] << " ";
if (((i+1) % 5) == 0)
{
cout << endl;
}
}
cout << endl;
return true;
}
}
class HistogramClass
{
private:
double minBinValue; //specified by user
double maxBinValue; // specified by user
int numbBins; //specified by user, max of 10
int histoBinCounts[MAX_BINS];
public:
bool setupHistogram(); //prototype function
bool addDataToHistogram(SamplingClass &sampling);//protype function
bool printHistogramCounts();
bool displayHistogram();
};
bool HistogramClass::setupHistogram()
{
cout << "Enter minimum value:";
cin >> minBinValue;
cout << "Enter maximum value:";
cin >> maxBinValue;
cout << "Enter number of bins:";
cin >> numbBins;
cout << "\n";
if (numbBins <= MAX_BINS)
{cin >> numbBins;}
else
cout << "Sorry, the maximum amount of bins allowed is 20. Try again!\n";
}
//function for the menu options that display to user
int promptUserAndGetChoice()
{
cout << "1. Enter a sample set of data values\n";
cout << "2. Print the contents of the current sample set\n";
cout << "3. Reset / Provide values for setting up a histogram\n";
cout << "4. Add the contents of current sample set to histogram\n";
cout << "5. Print bin counts contained in histogram\n";
cout << "6. View the histogram in graphical form\n";
cout << "0: Exit the program\n\n";
}
int main()
{
const int enter_option = 1;
const int printContents_option = 2;
const int reset_option = 3;
const int add_option = 4;
const int printBin_option = 5;
const int viewHist_option = 6;
const int exit_option = 7;
int menuChoice;
SamplingClass sampleSet;
HistogramClass histoSet;
do
{
promptUserAndGetChoice();
cout << "Your Choice: ";
cin >> menuChoice;
if (menuChoice == 1)
{
sampleSet.readFromKeyboard();
cout << "Last Operation Successful: YES\n\n";
}
else if (menuChoice == 2)
{
sampleSet.printToScreen();
}
else if (menuChoice == 3)
{
histoSet.setupHistogram();
}
}
while (menuChoice != 7);
return 0;
}

Each bin in a histograms is typically the same size. So when the user gives you the min, max and number of bins, you can compute the size, and therefore the range, of each bin. Each bin will be of size
bin_size = (max-min)/#_of_bins.
Now to figure out which bin a value goes into, compute
bin = ceil(value/bin_size)
(Or take the floor if you start numbering your bins at 0). And increment the count in this bin. Once you do this for all values, you can print out the count in each bin and this is your histogram.
Update: If min != 0, then the formula is:
bin = (int) (value-min)/bin_size
Using the cast here b/c codemesserupper can't use libs. bin here will be 0-indexed.

If you know the min and max, then any particular value x should be considered to fall into the array at index:
(x - min) / (max - min) * #bins
This will span the range 0..#bins inclusive, so just round down from #bins to #bins-1 when necessary.
EDIT: to be more explicit, and ignoring the object boundaries, the basic approach is to 0 the histoBinCounts then:
for (int i = 0; i < numbOfValues; ++i)
{
double x = sampleValues[i];
int bin = (x - minBinValue) / (maxBinValue - minBinValue) * numbBins;
if (bin >= 0 && bin < numbBins)
++histoBinCounts[bin];
}

Related

How to print product of all inputted numbers using a loop?

int main() {
cout << "Enter some numbers fam! " << endl;
cout << "If you wanna quit, just press q" << endl;
int n{ 0 };
int product = 1;
char quit = 'q';
while (n != 'q') {
cin >> n;
product = product* n;
cout <<"The product is : " << product << endl;
}
cout << endl;
cout << product;
return 0;
}
Whenever I print it out and cut the code using 'q', it prints me an infinite amount of "The product is 0". Also, how can I print out the final product of all numbers at the end?
So, there are some problems in your code.
First, you are taking input and assigning it to an int, which might not have been a problem, but you are also comparing the int to a char(which will cause problems in your case)
int n{ 0 };
while(n != 'q') {
cin >> n;
}
To solve that, you can make the n a string and then convert it into an integer with stoi(n) to use with the calculation
string n; // don't need to initialize a string, they are initialized by default.
int product = 1;
cin >> n; // Taking input before comparing the results
while(n != "q") { // Had to make q a string to be able to compare with n
product *= stoi(n); // Short for product = product * stoi(n)
cout <<"The product is : " << product << endl;
cin >> n; // Taking input for the next loop round
}
cout << endl;
cout << product;

How would I calcuate the total of all the items entered to then calculate the total price?

Hi there apologise if my question is poorly worded, I'm struggling to find a solution to my problem.
The purpose of my program is to allow the user to enter predefined bar codes that associate with items and a price. The user enters as many barcodes as they want, and when they're done they can exit the loop by pressing "F" and then total price for all the items is displayed.
This is my code so far, I'm very new to programming..
#include <iostream>
#include <iomanip>
using namespace std;
int index_of(int arr[], int item, int n) {
int i = 0;
while (i < n) {
if(arr[i] == item) {
return i;
}
i++;
}
return -1;
}
const int SIZE = 10;
int main()
{
string item [SIZE] = {"Milk", "Bread", "Chocolate", "Towel", "Toothpaste", "Soap", "Pen", "Biscuits", "Lamp", "Battery"};
int barcode [SIZE] = {120001, 120002, 120003, 120004, 120005, 120006, 120007, 120008, 120009, 120010};
float price [SIZE] = {10.50, 5.50, 8.00, 12.10, 6.75, 5.20, 2.00, 4.45, 20.50, 10.00};
cout << "*************************************************************" << endl;
cout << "WELCOME TO THE CHECKOUT SYSTEM" << endl;
cout << "Please scan a barcode or manually enter the barcode ID number" << endl;
cout << "*************************************************************\n" << endl;
int newBarcode;
while (true){
cout << "Please enter a barcode (Type 'F' to finish): ", cin >> newBarcode;
int index = index_of(barcode, newBarcode, (sizeof(barcode) / sizeof(barcode)[0]));
cout << "\n>> Name of item: " << item[index] << endl;
cout << ">> Price of item: \x9C" << setprecision (4)<< price[index] << endl;
cout << ">> " <<item[index] << " has been added to your basket. \n" << endl;
float total = 0 + price[index];
cout << ">> Your current basket total is: \x9C" << setprecision(4) << total << endl;
/*float total = 0;
float newtotal = 0;
price[index] = total;
total = newtotal;
cout << ">> " << "Basket total: " << newtotal << endl; */
}
return 0;
}
You will need to iterate over all items and add their value to a variable. You can do it the old way:
float sum = 0;
for(int i = 0; i < SIZE; i++) {
sum += price [i];
}
Or the C++11 way:
float sum = 0;
for(float p : price) {
sum += p;
}
However I must point out a few important issues with your code:
Your array has a fixed size but user can enter as many entries as he wants. To avoid this issue, use vector. It behaves like array but has dynamic size. Simply use push_back() to add a new element.
Don't use separate containers (arrays) for the same group of objects. It's a bad coding practice. You can define a structure for product which will contain name, barcode and price, then make one container for all of the products.
Edit
I'm sorry, I misunderstood your problem. There are many ways to solve this, the most elegant way is to create a map where key is the bar code and value is your product object or just a price.
map<int, float> priceMap;
priceMap.insert(pair<int, float>([your bar code here], [your price here]))
Afterwards just create a vector of bar codes, fill it with user data and iterate over it sum all prices:
float sum = 0;
for(int b : userBarcodes) {
sum += priceMap.at(b);
}
You are trying to read from cin into an int. As you decide to put a stopping condition on 'F' input you must read into a string. Then decide what to do with the value. You will need to check if the input is an int or not. You can do it as given here or here.
Or you may change the stopping condition to a less likely integer like -1. And make sure you always read an int into newBarcode.
There are various small errors which are hard to list out. I have changed them in the code below which is implementing point 2 (You have to add the stopping condition).
One of the error or wrong practice is to declare new variables inside a loop. In most cases you can declare the variables outside and change there values in the loop.
I replaced (sizeof(barcode) / sizeof(barcode)[0] with SIZE as the lists are predefined and unchanging. Anyways you should use (sizeof(barcode) / sizeof(barcode[0]) for length calculation.
#include <iostream>
#include <iomanip>
using namespace std;
int index_of(int arr[], int item, int n) {
int i = 0;
while (i < n) {
if(arr[i] == item) {
return i;
}
i++;
}
return -1;
}
const int SIZE = 10;
int main()
{
string item [SIZE] = {"Milk", "Bread", "Chocolate", "Towel", "Toothpaste", "Soap", "Pen", "Biscuits", "Lamp", "Battery"};
int barcode [SIZE] = {120001, 120002, 120003, 120004, 120005, 120006, 120007, 120008, 120009, 120010};
float price [SIZE] = {10.50, 5.50, 8.00, 12.10, 6.75, 5.20, 2.00, 4.45, 20.50, 10.00};
cout << "*************************************************************" << endl;
cout << "WELCOME TO THE CHECKOUT SYSTEM" << endl;
cout << "Please scan a barcode or manually enter the barcode ID number" << endl;
cout << "*************************************************************\n" << endl;
int newBarcode;
float total = 0;
int index;
while (true){
cout << "Please enter a barcode (Type -1 to finish): \n";
cin >> newBarcode;
while(cin.fail()) {
cout << "Not an integer" << endl;
cin.clear();
cin.ignore(100,'\n');
cin >> newBarcode;
}
index = index_of(barcode, newBarcode, SIZE);
cout << index;
if (index == -1) {
cout << "Apologies here for unsupported barcode\n";
continue;
} else {
cout << ">> Name of item: " << item[index] << endl;
cout << ">> Price of item: " << price[index] << "\n";
cout << ">> " <<item[index] << " has been added to your basket. \n";
total = total + price[index];
cout << ">> Your current basket total is: " << total << "\n";
}
}
return 0;
}
Your question could be more helpful to others if you find out what is wrong with your implementation and ask implementation specific questions which will probably be already answered. Asking what is wrong with my code is not quite specific.

How to use a while loop with an array?

I've created a program that allows the user to enter 10 grades. I've used a while loop to store grades in the array, but if the user only has 5 grades to input, he can type done to exit the program.
After the loop has finished, it will then calculate and display. the highest grade, lowest grade, and the average grade within the array
Unfortunately, when the user types done, the program will display the rest of the grade lines that were not entered.
Can you help me find out how to stop the while loop from displaying the rest of unentered grades of the loop?
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 10;
int grade[SIZE];
int count = 0;
int lowestGrade;
int highestGrade;
bool done = false;
cout << "This program is limited to entering up to 10 grades." << endl;
while ( grade[count] != done && count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
cin >> grade[count];
count++;
}
//LOWEST GRADE
lowestGrade = grade[0];
for (count = 0; count < SIZE; count++)
if (grade[count] < lowestGrade)
{
lowestGrade = grade[count];
}
//HIGHEST GRADE
highestGrade = grade[0];
for (count = 0; count < SIZE; count++)
{
if (grade[count] > highestGrade)
{
highestGrade = grade[count];
}
}
//AVERAGE GRADE
double total = 0;
double average;
for (int count = 0; count < SIZE; count++)
total += grade[count];
average = (total / SIZE);
cout << endl;
cout << "Your highest grade is: " << highestGrade << endl;
cout << "Your lowest grade is: " << lowestGrade << endl;
cout << "Your average grade is: " << average << endl;
system("pause");
return 0;
}
Here are two problems with your code.
First:
....
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
cin >> grade[count];
count++;
....
The code above will attepmpt to read word "done" into integer variable, producing 0. Not what you want to do!
Second:
...
for (count = 0; count < SIZE; count++)
...
Code above will try to iterate over all possible elements (SIZE). However, you might have enetered less than that! You need to use count calculated in the previous loop as your boundary (and of course, use a different name for control variable in the loop).
There are a couple of things to unpack here.
Basically, the input you are retrieving is a char * and the >> operator is casting that to an int to fit into your array of grades.
Next what you are checking with grade[count] != done is if the integer in "grade" at the id "count" is not equal to the bool false. This will always return true in this case.
For your use case what you want to be checking is if your input is equal to the char * "done"
This cannot be happening in the predicate of the while loop because your grade array stores only int.
Therefore the simplest solution to the problem in my opinion, is to check whether the input is equal to "done".
If it is you want to set the done boolean to true
Otherwise we can try to cast it to an int and store that in the grades array.
Here is the revised loop:
while (!done && count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
string input = "";
cin >> input;
if (input == "done")
{
done = true;
}
else
{
grade[count] = stoi(input);
}
count++;
}
The following is somewhat outside the scope of the question, but an additionnal advantage to using stoi() is that it ignores input that is not a number, which will shield against someone entering invalid input like "potato". This is why I immediately cast the input into a string.
Use another variable to store the amount ofgrades the user entered. You also cannot store a string in your integer array:
std::string input = "";
while(count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
getline(cin, input);
if(input == "done")
break;
try
{
grade[count] = std::stoi(input);
count++;
}
catch(std::invalid_argument)
{
cout << "not a valid number\n";
}
}
int actualsize = count;
and then use this variable to abort your for loops:
for (int i = 0; i < actualsize; i++)
There are two simple ways to solve your problem:
You can read strings instead of integers and in case the read string is "done", break the loop, else, convert the read string to an integer, something as follows:
```
// rest of the code
int total_count = 0;
while (count < SIZE) {
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
string temp;
cin >> temp;
if(temp == "done") {
break;
} else {
grade[count] = stoi(temp);
count++;
total_count = count;
}
}
// rest of the code
```
If you don't want to use strings, then, assuming grades will be non-negative, you can stop reading input when the user types a negative number, say "-1". So, you will need to do something as follows:
```
// rest of the code
int total_count = 0;
while (count < SIZE) {
cout << "Enter a grade #" << count + 1 << " or -1 to quit: ";
int temp;
cin >> temp;
if(temp == -1) {
break;
} else {
grade[count] = temp;
count++;
total_count = count;
}
}
// rest of the code
```
Also, don't forget to replace SIZE by total_count in rest of the loops i.e. the ones computing 'LOWEST GRADE', 'HIGHEST GRADE' and 'AVERAGE GRADE'.
NOTE: You will have to do #include <string> at the top as well, if you use the first option.

c++ Division . seemingly simple thing driving me crazy, advice please

Ok i've been programming for about a week now, i started with c++. I'm writing a program that is a kind of an arithmetic trainer, you enter the amount of equations you want, you enter your limit for the random number generator, you specify what kind of equations you want(/*-+), then the program uses a for loop and goes through and generates the equations and their answers in a var and then the users input is checked against this var and if they match another var which is counting the right answers is incremented. After the last equation the program tells the user how many they got right out of how many equations, and by dividing the amount of right answers by the amount of questions then multiplying this value by 100 u should obtain the accuracy percentage for this users arithmetic session. Problem is c++ keeps returning to me a friggin 0 value and i cannot for the life of me work out why in the world c++ is doing this.
entire program:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
void menu(void);
class session{
public:
session(){
create_session();
}
void create_session(void){
amount = 0;
range_limit = 0;
rights = 0;
answer = 0;
input = 0;
type = "";
while(amount == 0){
cout << "\nHow many equations do you want?: "; cin >> amount;
if(amount < 1){
cout << "\nAmount is too low!";
amount = 0;
}
}
while(range_limit == 0){
cout << "Enter the number range limit: "; cin >> range_limit;
if(range_limit < 1){
cout << "\nRange limit too low!";
range_limit = 0;
}
}
while(type == ""){
cout << "What equation type do you want?: "; cin >> type;
int strlen = type.size();
if(strlen < 1){
cout << "Invalid type input!";
type = "";
}
}
if(type == "+"){
for(int i=0;i<amount;i++){
int a = random();
int b = random();
answer = a + b;
cout << "\n" << a << " + " << b << " = "; cin >> input;
if(answer == input){
rights++;
}
}
}
cout << "\nYou got " << rights << " answers right out of " << amount << " equations." << endl;
cout << "Accuracy percentage: " << getAccuracy() << "%" << endl;
int post_menu=0;
while(post_menu == 0){
cout << "Enter 1 to create another session or 2 to return to the menu: ";
cin >> post_menu;
if(post_menu == 1){
create_session();
}else if(post_menu == 2){
menu();
}else{
cout << "Invalid input: ";
post_menu = 0;
}
}
}
float getAccuracy(){
float x = (rights/amount)*100;
return x;
}
int random(){
int x = 1+(rand()%range_limit);
return x;
}
void set_amount(int a){
amount = a;
}
void set_range_limit(int r){
range_limit = r;
}
void set_rights(int R){
rights = R;
}
void set_answer(int a){
answer = a;
}
void set_input(int i){
input = i;
}
void set_type(string t){
type = t;
}
private:
int amount;
int accuracy;
int range_limit;
int rights;
int answer;
int input;
string type;
};
int main(){
cout << "=== WELCOME TO ARITH! === \n=========================\n";
menu();
return 0;
}
void menu(void){
//Set the seed for random number gen.
srand(time(0));
//Set var for getting menu input, then get the menu input..
int menu_input;
cout << "\n[1]Create a Session. [2]Exit Arith. \nWhat would you like to do?: ";
cin >> menu_input;
//Now we check what the user wants and act accordingly..
if(menu_input > 2){
cout << "error";
menu_input=0;
}else if(menu_input == 1){
session start;
}else if(menu_input == 2){
cout << "\nExiting Arith!";
}else{
cout << "error";
menu_input=0;
}
}
Troublesome part:
float getAccuracy(){
float x = (rights/amount)*100;
return x;
some how the program is returning 0%.
anyone know why this is so and how to get the result im after.
rights and amount both are int , so when you divide the value is floored, for example if you do 5/2 the answer would be 2 instead of 2.5. To solve this you need to cast one of the variable to float like this: (float(rights)/amount) * 100.
when two int numbers are divided the result will also be int even if temporary variable. so you can make any of the variable float or double or cast it.
You need to convert only one data type because the other will be type promoted implicitly.
float x = ((double)rights/amount)*100;
or you can make your amount variable float by default if it doesnt affect any other part of your code.
Also you have the option to static cast:
float x = (static_cast<double>(rights)/amount)*100;

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.