C++ Array parameters and const value - c++

I do not get arrays, Im sure there are easier ways to make this program but I must do it the teacher's way and I am lost.
This is the assigment:
I do not get how I should go about these arrays. most confusing thing I seen by far.
What I would like is a guide or help on how i should program these arrays or how I should program arrays period. Not asking to do the rest for me, I already know how to do most of this, its just the arrays I like to know how to do.
This is my current program:
#include<iostream>
using namespace std;
void getPoints(int pPossible[], double pEarned[], int numItems, int limit);
int sumArray(double
void getpoints(int pPossible[], double pEarned[], int numItems, int limit)
{
int count;
while (limit == limit)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numbItems > limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
count=1;
for(count=1; count<numItems; count++)
cout << "Enter points then points possible for Item " << count << ": ";
cin << pEarned[count] << pPossible[count];
return 0;
}

C++ array indexes are zero-based, so you should use zero for the initial value in the for loop. Also, you're missing the braces for the for loop body; as it is, it will run the cout line numItem-1 times and the cin line just once.
Another thing: the operators in the for's cin line should be >>, not <<. You want input here, not output.
Finally, like #ebyrob said, make numItems a reference parameter (it would be clearer for the caller to use a pointer instead, but the assignment asked for a reference parameter).
void getpoints(int pPossible[], double pEarned[], int& numItems, int limit)
{
//Read number of items
while (true)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numItems >= limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
//Read earned and possible for each item
for(int count=0; count<numItems; count++)
{
cout << "Enter points then points possible for Item " << count << ": ";
cin >> pEarned[count] >> pPossible[count];
}
return 0;
}

Related

adding digits in an array c++

I'm new to C++ and i was trying to understand how to work with arrays. The idea I have is:
I wanted a user to input an array, the program to output the
array
Double all the values in the array and output that
And for each of the doubled values, add the digits of the doubled number
(1 digit number would remain the same), then output the new numbers as
well.
(e.g. if the array was [5, 6, 7, 8], the doubled values would be [10, 12, 14, 16] and then you would add each values digits like, [1+0, 1+2, 1+4, 1+6] to get [1, 3, 5, 7].
I put my code to show my progress, feel free to point out any errors along the way!
Any help is appreciated!
p.s. The nested loop didn't work :(
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum-1;i++)
cout << num[i];
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum-1;j++)
{
num[j]*=2;
cout << num[j];
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
for (int k=0;k<maxNum;k++)
{
for (int l=0;l<maxNum;l++)
{
int sum[20];
while (num[k]!=0)
{
sum[l]=sum[l]+num[k]%10;
num[k]=num[k]/10;
}
}
cout << sum[l];
}
cout << endl;
}
A few things:
maxNum and num[] are never initialized, it's dangerous.
that is not how you scan input. Ideally you woud do smth like while(cin >> tem_var){}. Or you could modify it to be if( !(cin >> num[i]) ) break;. That way you don't need to do maxNum-1 later too. (cin>>) will be True if it reads a variable succesfully and False otherwise. That way you can stop scanning by entering any non-number string, instead of running the loop for the rest of iterations, but leaving num[i] uninitialized if that happens.
you forget to output delimeters between array numbers which makes it hard to read.
cout << num[i] << "|"; or smth.
In the last part you make 3 loops: a k for loop that you never use, a l for loop to iterate num, and a k while loop to sum the digits. One of them is not necessary.
In the last part sum[] array, though filled correctly, is not outputted. You declare it inside the l loop, meaning it's deleted when you exit it. And even if you declared it outside. your cout << sum[l]; is outside the l loop, meaning it will only try to do the cout << sum[maxNum]; (the value of l the loop finishes with) while you only have [0:(maxNum-1)] elements in num and sum filled.
I'd suggest you try smth like for(k=1;k<num[l];k*=10) sum[l]+= num[l] / k % 10; instead of that while loop. It's shorter, gets the job done and leaves num[l] unchaged in case you decide to use it again afterwards.
You need to initialize sum array with all zeros first. You don't need nested loop.
Create a sum array to store the sum of each number and initialize it with 0's. First write a loop to traverse through the elements of the doubled array. For each element write a loop(you chose while loop) to traverse through the digits of each number and them to the corresponding sum element.
I've modified your code a little bit, go through it once.
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum-1;i++)
cout << num[i]<<' ';
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum-1;j++)
{
num[j]*=2;
cout << num[j]<<' ';
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
int sum[20];
for (int i=0;i<maxNum-1;i++)
sum[i]=0;
for (int k=0;k<maxNum-1;k++)
{
// for (int l=0;l<maxNum;l++)
// {
while (num[k]!=0)
{
sum[k]=sum[k]+num[k]%10;
num[k]=num[k]/10;
}
cout << sum[k]<<' ';
// }
}
cout << endl;
}
You don't need nested loop for that ,while making logic behind any program take a simple example and get the result,Don't jump directly to code. This will help you to building logics.
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
int sum=0;
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum;i++)
cout << num[i]<<ends;
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum;j++)
{
num[j]*=2;
cout << num[j]<<ends;
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
int r=0;
for (int k=0;k<maxNum;k++)
{
while (num[k]>0)
{
r=num[k]%10;
sum+=r;
num[k]=num[k]/10;
}
cout<<sum<<ends;
sum=0;
r=0;
}
cout << endl;
}

I keep getting a variable uninitialized error when calling a function that is asking for user input

#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int numofEmployees();
int daysMissed(int);
int AverageMissed(int, int);
int main()
{
cout << "Welcome to employee absentee calculator!" << endl;
int numEmployees = numofEmployees();
int Missed = daysMissed(numEmployees);
double misAverage = AverageMissed(numEmployees, Missed);
cout << "There are " << numEmployees << " in the company. They have missed " << Missed << " days total. On average, they have missed " << misAverage << " days." << endl;
return 0;
}
int numofEmployees() {
cout << "How many employees are in your company? ";
int employees;
cin >> employees;
while (employees < 1) {
cout << "Employee count must 1 or greater!" << endl;
}
return employees;
}
int daysMissed(int numEmployees) {
int Absence, totAbsence = 0;
for (int i = numEmployees; i < numEmployees; i++) {
cout << "How many days has each employee missed this passed year? ";
cin >> Absence;
totAbsence += Absence;
}
while (Absence < 0) {
cout << "Values entered must be positive numbers!" << endl;
cin >> Absence;
}
return totAbsence;
}
int AverageMissed(int numEmployees, int Missed){
double Average;
Average = double(numEmployees) / double(Missed);
return Average;
}
This code is being used to calculate the average number of employee absences by way of using three functions. The second function is not working correctly as it is not being called properly by the main. This is for a school assignment.
The problem is daysMissed - if numEmployees is <= 0, then Absense will be uninitialized. But, you say, "I check that in numofEmployees" - the problem is that the compiler doesn't do that sort of whole-program analysis before issuing these warnings.
There is another problem: daysMissed is wrong (twice). If there are two employees, and I enter -2 and 1, there will be no error for the negative number. If on the other hand, if I enter 1 and -2, you never correct totAbsence. You would be much better off writing a little function which reads a number >= some limit in a loop, and keeps prompting until given the correct value. Something like:
int read(const char* prompt, const char* err_prompt, int limit) {
cout << prompt << endl;
for(;;) {
int result;
cin >> result;
if (result >= limit) {
return result;
}
cout << err_prompt << endl;
}
}
Then daysMissed becomes much pleasanter to write - and you can use the same function to read the number of employees (which will go into an infinite loop at the moment)
You should also validate a division by zero plus change the return type.
double AverageMissed(int numEmployees, int Missed){
if (Missed > 0) return double(numEmployees) / Missed;
return 0;
}
by the way, there is no need to cast both operands in the division (/). Casting one of them will be enough to return a double type.

Calling c++ functions

this is my first question here on stackoverflow so I hope it all comes out formatted correctly. I'm working on an assignment for my programming course and we have to write a program that takes two inputs and then produces a readout of results. I had to create two functions that ask which concert a person would like to attend and then how many tickets they would like to purchase for that concert. I've created the functions but now I'm having trouble calling the functions in order to print my results.
#include <iostream>
using namespace std;
char GetConcert()
{
char Concert;
cout << "The following concerts are available:\n";
cout << " B for Beyonce\n";
cout << " L for Lady Gaga\n";
cout << " T for Taylor Swift\n";
cout << "Enter the letter for the concert you want:\n";
cin >> Concert;
return Concert;
}
int GetNumTickets()
{
int NumTickets;
cout << "Enter the number of tickets you want:\n";
cin >> NumTickets;
while ((NumTickets < 0) || (NumTickets > 10))
{
if (NumTickets < 0)
cout << "You can not sell tickets here.\n";
else if (NumTickets > 10)
cout << "You may not purchase more than 10 tickets.\n";
cout << "Enter the number oftickets you want:\n";
cin >> NumTickets;
}
return NumTickets;
}
int main()
{
// Declare Variables
char Concert;
int NumTickets;
// Call function to find out the concert they want to attend
// Call function to find out how many tickets they want
// Print out the information you have collected.
cout << "\nThe customer has placed the following order:\n";
cout << "Concert: " << Concert << endl;
cout << "Number of Tickets: " << NumTickets << endl;
return 0;
}
I've declared my variables in the main section, but when I try to call the function, it says that I can't switch from integer to character.
In order to call a function in c++ you need () at the end of the function name. In this example GetNumTickets() and GetConcert(). Since these functions are also returning values, it is important to save the returned values in order to use them later or to use them right away. You could try:
char Concert = GetConcert();
int NumTickets = GetNumTickets();

Numbers game C++

I have a program that stores current a low numbers. The Object is to Store the low number every time time a new number is presented. so say I start the function the first number will equal the low number. but the trouble im having it once the function is called again it starts over and low is erased. Is there a way I can keep the function value once the function is called again? or does anyone know a better way of doing this while keeping function in a class?
Thanks
double a;
class rff{
public:
void FGH()
{
double b=0;
cout<< "pick a number"<<endl;
cin>>a;
b=a;
cout << "yournum";
cout << "LAST num:" << a<< endl;
cout << "Low num:" << b << endl;
cout <<"'pick another number"<<endl;
cin>>a;
if (a < b)
{
b = a;
}
cout << "yournum";
cout << "LAST num:" <<a<< endl;
cout << "Low num:" << b<< endl;
cin.get();
}
};
and source CPP
int main(){
rff ws;
ws.FGH();
ws.FGH();
ws.FGH();
cin.get();
cin.get();
return 0;
}
There is many mistakes in your code. Here I suggest something probably better (not tested, so you will maybe need to adapt it).
class MinimalChecker {
private:
double minValue;
public:
void MinimalChecker() {
minValue = std::numeric_limits<double>::max();
}
void check()
{
double userInput = 0;
cout << "Pick a number" << endl;
cin >> userInput;
if (userInput < minValue)
{
minValue = userInput;
}
cout << "Number typed:" << userInput << endl;
cout << "Lower number:" << minValue << endl;
cin.get();
}
};
Changes:
Better class/method names, easier to understand
No more global variable. Only a class member which store the minimal value starting when user has entered a number for t-he first time. It is initialized in the constructor with max value allowed by double type in c++.
Number is asked to user only one time. If you don't do that, each time you run your old FGH() function, the lower number is overriden without condition.

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.