C++ array structures - c++

I was reading the chapter on structures in my book, and it got me re-modifying a program I already made, but this time using structures which I have never used before; however, after finishing the program, there's one issue I'm not understanding. The output of the program only displays once. It's in a for loop, and yet even though it asks me to input my information three times, it only outputs the first information.
I'm probably just not understanding how arrays in structures work.
An example of my issue is the following.
I have my output on the following loop
for(int counter = 0; counter <size; counter++)
The size is 3, which would mean I'll get the output printed three times; however the answer I'm getting is the same as if I was asking for the following.
Listofnames[0].F_name
When what I actually want is
Listofnames[0].F_name Listofnames[1].F_name Listofnames[2].F_name
However, I don't want to have to write it three times, I did to test it and it actually worked, but is that the only way to do it? Or did I miss something in my program?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Names
{
string F_name; //Creating structure called Names.
string L_name;
char Mi;
};
struct Payrate
{
double rate;
double hoursworked; //Creating structure called Payrate.
double gross;
double net;
};
int main()
{
double stateTax = 0, federalTax = 0, unionFees = 0, timeHalf = 1.5; //Initializing variables.
const int size = 2; //Array size.
Payrate employee[size]; //Structure variables
Names Listofnames[size];
for (int counter = 0; counter < size; counter++) //Initializing for loop.
{
cout << "What's your first name?: " << endl;
cin >> Listofnames[counter].F_name;
cout << "What's your last name?: " << endl; //Displaying names, and hours worked, rate.
cin >> Listofnames[counter].L_name;
cout << "What is your middle initial?: " << endl;
cin >> Listofnames[counter].Mi;
cout << "How many hours did you work? Please enter a number between 1-50: " << endl;
cin >> employee[counter].hoursworked;
cout << "What is your hourly rate? Please enter a number between 1-50: " << endl;
cin >> employee[counter].rate;
if (employee[counter].hoursworked < 0 || employee[counter].hoursworked >50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].rate < 0 || employee[counter].rate > 50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].hoursworked <= 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * employee[counter].rate; //Calculating gross.
}
else if (employee[counter].hoursworked > 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * (employee[counter].rate * timeHalf); //Calculating gross.
}
stateTax = employee[counter].gross * 0.06;
federalTax = employee[counter].gross * 0.12; //Calculates all the tax fees, and net.
unionFees = employee[counter].gross * 0.02;
employee[counter].net = employee[counter].gross - (stateTax + federalTax + unionFees);
}
cout << "FirstN " << "MI " << "LastName " << "\t" << "Rate " << "HoursWorked " << "TimeHalf " << "StateTax " << "FederalTax " << "UnionFees " << "Gross " << " " << "Net " << endl; //Displays header of output.
cout << "==================================================================================================================" << endl;
for (int counter = 0; counter <= size; counter++)
{
//Output.
cout << Listofnames[counter].F_name << "\t" << fixed << setprecision(2) << Listofnames[counter].Mi << " " << Listofnames[counter].L_name << "\t" << employee[counter].rate << "\t" << employee[counter].hoursworked << "\t" << setw(7) << timeHalf << "\t" << setw(8) << stateTax << setw(12) << federalTax << "\t" << unionFees << "\t" << employee[counter].gross << "\t" << employee[counter].net << endl;
system("pause");
}
}
P.s If you had to re modify this program again, what would you use to simplify it. Asking so I can keep re-modifying, and learn more advanced stuff. Vectors, pointers? Thanks in advance.

You have an array with 3 indexes but your loop is only going upto 2 indexes. Change your for loop to this.
for (int counter = 0; counter <= size; counter++)
Now, this loop will print the all the indexes.
Instead of using a static value you can also use this.
for (int counter = 0; counter < sizeof(Listofnames)/sizeof(Listofnames[0]); counter++)
sizeof(Listofnames)/sizeof(Listofnames[0]) This will give you the total size of your array.
Ideone Link

Related

Adding all value to total in for loop

I'm new to coding. I wrote the below code in C++ and I am not allow to use array.
You will create a console C++ program that uses a nested loop to enter each archer's individual end scores and then displays the total score for each archer.
I am stuck at how to calculate the total end score:
#include <iomanip>
using namespace std;
int main()
{
int Rounds = 4;
int Archers = 3;
int endScore ;
int average;
for (int a = 1; a <= Archers ; a++)
{
cout << endl << "Number " << a << " score" << endl;
int tEndScore = 0 ;
for(int i=1; i <=Rounds ; i++)
{
cout << "Round " << i << " : " ;
cin >> endScore;
while(cin.fail())
{
cout << endl << "not enter an integer " << endl ;
cout << "Please enter an integer ";
cin >> endScore;
}
tEndScore += endScore;
}
cout << endl << "The total score for 4 ends of Archer Number " << a << " is " << tEndScore << endl;
average =(double) tEndScore/Rounds;
cout << setiosflags(ios::fixed) << setprecision(2) << endl << "The average score of 4 ends of Archer Number " << a << " is " << average << endl;
}
}
This is the result after running. It will only use the last value I entered as tEndScore:
You need to shift tEndScore =+ endScore; this line inside the second for loop as
for(int i=1; i <=Rounds ; i++)
{
...
...
tEndScore += endScore;
}
And it will be a good practice (And mandatory for your code...) to initialize the tEndScore for each player as
for (int a = 1; a <= Archers ; a++)
{
tEndScore = 0;
endScore = 0;
average = 0;
...
...
}
You need to replace totalEndScore to tEndScore and totalRounds to Rounds.

How can I do this without arrays or vectors only using loops

I am almost done with this project just stuck on this last part. Really need help I've reach out to teacher not getting a response. I want to display which complex enter has the highest rent total. Right now I have a double named currentRentAmount which keeps a running total after each loop it reset. So the issue is if the first complex enter was the highest rent collected complex enter it loses that value because its reset to 0. I feel so close yet so far a way. I cant use vector/ array because we technically haven't learn it yet.
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ofstream outputFile;
outputFile.open("rentfile.txt");
int numComplex, numMonths;
double rent, totalAllRent = 0; //// Accumulator for total scores
string nameComplex;
string highNameComplex;
double averageRent;
double highestComplexRent = 0;
double currentRentAmount = 0;
double previousRentAmount = 0;
//set up numeric output programing
cout << fixed << showpoint << setprecision(1);
cout << "How many complexes will you enter?";
cin >> numComplex; //number of complexes enter
cout << "How many months of rent will you enter complex?";
cin >> numMonths; //number of months of rent enter
for (int complex = 1; complex <= numComplex; complex++)
{
cout << "Enter Complex Name ";
cin >> nameComplex;
outputFile << nameComplex << " ";
for (int months = 1; months <= numMonths; months++)
{
cout << "Enter Rent " << months << " for ";
cout << " Complex " << complex << ": ";
cin >> rent;
totalAllRent = totalAllRent + rent;
averageRent = totalAllRent / numComplex;
outputFile << rent << endl; //write data to output file
currentRentAmount = currentRentAmount + rent;
cout << currentRentAmount << endl;
if (currentRentAmount > highestComplexRent)
{
currentRentAmount = highestComplexRent;
}
}
currentRentAmount = 0;
}
outputFile.close(); //close the file
ifstream inputFile;
inputFile.open("rentfile.txt");
cout << "Complex Monthly rent Collected per Complex " << endl;
while (inputFile >> nameComplex)
{
for (int i = 0; i < numMonths; i++)
{
inputFile >> rent;
cout << nameComplex << " " << rent << endl;
if (rent == 0)
cout << "Warning one of the complexes submitted zero rent for one of the months " << endl;
}
}
cout << "Total rent collected for the company = " << totalAllRent << endl;
cout << " Average Monthly rent collected for the company = " << averageRent << endl;
cout << highNameComplex << "collect the most rent = " << highestComplexRent << endl;
system("pause");
return 0;
}
First a friendly note; 'Complex number' means something very specific , you are talking about apartment complex numbers. However, when most people read complex number they think x+iy (think imaginary numbers)
Second , the problem you have is one of logic. You want to find the apt complex with the highest rent, but you seem to update the highest rent value in this condition.
if (currentRentAmount > previousRentAmount)
{
highestComplexRent = currentRentAmount;
}
Ask yourself why you are doing this , what happens in every iteration of the loop. IF currentRentAmount > previousRentAmount since previousRentAmount is always 0.Effectively, this means, if the value of current rent is greater than 0 highest rent is set to current rent.
What you want here is:
1. Make sure highestRentAmount is set to 0 outside of the loops.
2. The if check should be if(currentRentAmount > highestComplexRent) (think through why this will work, I can tell you the answer, but just think about it for a second, its much better to arrive at it yourself)
Good luck
You can use a variable maxComplexRent to keep the track of complexRent.
double maxComplexRent = 0.0;
for (int complex = 1; complex <= numComplex; complex++)
{
cout << "Enter Complex Name ";
cin >> nameComplex;
outputFile << nameComplex << " ";
for (int months = 1; months <= numMonths; months++)
{
cout << "Enter Rent " << months << " for ";
cout << " Complex " << complex << ": ";
cin >> rent;
totalAllRent = totalAllRent + rent;
averageRent = totalAllRent / numComplex;
outputFile << rent << endl; //write data to output file
currentRentAmount = currentRentAmount + rent;
cout << currentRentAmount << endl;
}
//Here
maxComplexRent = maxComplexRent>currentRentAmount? maxComplexRent:currentRentAmount;
currentRentAmount = 0;
}
Few suggestions here:
It does not use the correct variable:
if (currentRentAmount > previousRentAmount)
should be changed to
if (currentRentAmount > highestComplexRent)
This line should be moved out to the outer loop (although it is unused):
averageRent = totalAllRent / numComplex;
Remove the unused variables.
if statement was wrong able to fix
if (currentRentAmount > highestComplexRent)
{
highestComplexRent = currentRentAmount;
}

Not outputting the calculation, just 0

I have my code here and it runs, however, when I try to output the percentage it just outputs 0, I've spent a long time trying to figure out what I'm missing and I'm clueless. Basically I'm trying to output the percent of votes for each candidate out of total votes. Any help would be appreciated. Here is my output;
Output display Also, im aware that the winner loops through every user until it reaches the end for some reason, still trying to work out the kinks.
Here is my code -
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class candidatesElection
{
public:
string last;
float votePercent;
void winnerOfElection();
void outputDis();
int total = 0;
};
int main()
{
string lastName[5];
int amountOfVotes[5];
double percentTotal[5];
int total = 0;
int winnerNo = 0;
int winningCandidate;
string winningName;
for (int i = 0; i < 5; i++)
{
cout << "Enter the last name of the Candidate: " << endl;
cin >> lastName[i];
cout << endl;
cout << "Enter the votes received by the Candidate: " << endl;
cin >> amountOfVotes[i];
total += amountOfVotes[i];
cout << "Total number of votes is: " << total << endl;
}
for (int i = 0; i < 5; i++)
{
if (amountOfVotes[i] > amountOfVotes[winnerNo]) winnerNo = i;
amountOfVotes[i] = amountOfVotes[winnerNo];
}
for (int i = 0; i < 5; i++)
{
percentTotal[i] = (amountOfVotes[i] / total) * 100.0; // need to make it floating point
}
void outputDis();
{
cout << endl << left << setw(25) << "Candidate" << right << setw(25) << "Votes Received" << setw(25) << "% of Total Votes" << endl;
for (int i = 0; i < 5; i++)
cout << endl << left << setw(25) << lastName[i] << right << setw(25) << amountOfVotes[i] << setw(25) << percentTotal[i] << endl;
cout << endl << left << setw(25) << "Total" << right << setw(25) << total << endl;
for (int i = 1; i < 5; i++)
{
int winHigh = amountOfVotes[0];
string win = lastName[0];
if (amountOfVotes[i] > winHigh)
{
winHigh = amountOfVotes[i];
win = lastName[i];
}
cout << "The Winner of the Election is " << win << endl;
}
}
system("pause");
};
The coefficient amountOfVotes[i] / total in (amountOfVotes[i] / total) * 100.0 is evalated in integer arithmetic: i.e. any fraction is discarded.
So you end up with 0 * 100 for all cases where amountOfVotes[i] is less than total.
The solution is to rearrange the formula to 100 * amountOfVotes[i] / total;, or, even better 100.0 * amountOfVotes[i] / total; which will force evaluation in double precision floating point - you are in danger of overflowing an int which, on some systems, can have an upper limit as low as 32767.
That's not immediately obvious even when using a line-by-line debugger. But do use that debugger to work out the other "kinks".

Float Variable Not Working Inside Switch Statment

So this program is supposed to collect weather temperatures over 7 days using a for loop and then basically just print them back out to the user with an average temperature and the highest recorded temperature. Keep in mind, the following piece of code is a part of a much larger program. Anyway, the problem seems to be the "highest_temp1" float variable. When I run the program it produces some sort of error code instead of the highest temperature. This piece of code was tested in a separate source file and it works no problem.
switch (choice)
{
case 3:
int n;
float temperatures [7];
float lastweektemp [7] = {12.56,8.65,7.5,10,7.9,5,8};
float highest_temp1, highest_temp2;
float accumulated_temp1, accumulated_temp2;
system("CLS");
cout << "____________Weather Data____________" << endl << endl;
for (n = 0; n<7; n++)
{
cout << "What is the temperature for Day " << n+1 << " ?" << endl;
cin >> temperatures[n];
if (highest_temp1 < temperatures [n])
{
highest_temp1 = temperatures [n];
}
if (highest_temp2 < lastweektemp [n])
{
highest_temp2 = lastweektemp [n];
}
accumulated_temp1 = accumulated_temp1 + temperatures[n];
accumulated_temp2 = accumulated_temp2 + lastweektemp [n];
}
cout << endl << " Day This Week Last Week" << endl;
for (n=0; n<7; n++)
{
cout << n+1 << temperatures[n] << lastweektemp[n] << endl;
}
system("CLS");
cout << " Weather Report" << endl;
cout << " --------------" << endl << endl;
cout << "Current Week: " << endl;
cout << "-------------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << temperatures[n] << endl;
}
cout << endl << " Average: " << accumulated_temp1 / 7 << endl;
cout << " Highest Temperature: " << highest_temp1 << endl;
cout << "Last Week: " << endl;
cout << "----------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << lastweektemp[n] << endl;
}
cout << endl << " Average: " << accumulated_temp2 / 7 << endl;
cout << " Highest Temperature: " << highest_temp2 << endl;
system("PAUSE");
}
The highest temperature in current week is 24 but it is printing "Highest Temperature: 3.45857e+032"
This exact 'error-code' is appearing every time I run the program it doesn't change.
I am a newbie hence why I can't upload a photo.
Any help would be appreciated. I'm doing a small assignment in college. This is my first question so go easy !!
You have not assigned any value to teh variable highest_temp1 and you are comparing it with another value.
Basically you will need to assign it a value first before you compare..
highest_temp1 = 10.00
(or anything that it is supposed to contain)
You have not initialised highest_temp1 (or highest_temp1 for that matter: after that I stopped looking).
Same for accumulated_temp, which gets not initialised. can be done via
float accumulated_temp1(0);
Initialize variables before using them
float highest_temp1(-FLT_MAX); // -FLT_MAX insures results of first compare
float highest_temp2(-FLT_MAX); // Could use -1.0/0.0 of -INFINITY instead
float accumulated_temp1(0.0);
float accumulated_temp2(0.0);
For float number condition use if statements switch is not able to work in case of float number, switch only work for integer number.

(C++) Code seems to be operating off the wrong loop...?

I've been playing around with some code in my down-time from my degree and I've nested a do{}while() loop inside another one but the problem I'm having is that the code keeps going until the last van is full, even after the number of parcels has been fulfilled...
The code's below. If someone could take a look at it and tell me what I've done wrong that'd be awesome. Bare in mind I've only really been coding in C++ for about a month so I've still got hella lot to learn..
#include <iostream>
using namespace std;
char cBeltFull;
int iVanCount, iParcelCount, iParcelLoaded;
float fHeaviestVanWeight, fParcelWeight, fCurrentPayload, fVanCapacity;
char cExit = 'N';
int main() {
iVanCount = 1;
iParcelLoaded = 1;
fHeaviestWeight = 0;
fVanCapacity = 410;
do {
//Get the number of parcels to dispatch
cout << "How many parcels need sending?" << endl;
cin >> iParcelCount;
do {
fCurrentPayload = 0;
do {
//Get parcel weight
cout << endl << endl << endl << "What is the weight the parcel " << iParcelLoaded << "?";
cin >> fParcelWeight;
//'Load' the parcel
cout << endl << endl << "Parcel loaded";
iParcelLoaded ++;
//Update the payload
fCurrentPayload = fCurrentPayload + fParcelWeight;
} while ((fCurrentPayload + fParcelWeight)) < fVanCapacity)
//Dispatch the van
cout << endl << endl << "Van dispatched.";
//Update the van count
iVanCount ++;
if (fCurrentPayload > fHeaviestVanWeight) {
//Update the heaviest weight
fHeaviestVanWeight = fCurrentPayload;
}
} while (iParcelLoaded <= iParcelCount);
cout << endl << endl << endl << "Vans dispatched: " << iVanCout;
cout << endl << endl << "Weight of heaviest van: " << fHeaviestWeight;
cout << endl << endl << endl << "Exit? Y for YES or N for NO." << endl;
cin >> cExit;
} while (cExit == 'N');
}
Change this
} while (((fCurrentPayload + fParcelWeight)) < fVanCapacity);
to this
} while (((fCurrentPayload + fParcelWeight)) < fVanCapacity
&& iParcelLoaded < iParcelCount);
That way you will load as many items the user inputs. You code contains many syntax errors.
I corrected them for you, but please be more careful next time you post.
#include <iostream>
using namespace std;
char cBeltFull;
int iVanCount, iParcelCount, iParcelLoaded;
float fHeaviestVanWeight, fParcelWeight, fCurrentPayload, fVanCapacity;
char cExit = 'N';
int main() {
iVanCount = 1;
iParcelLoaded = 1;
fHeaviestVanWeight = 0;
fVanCapacity = 410;
do {
//Get the number of parcels to dispatch
cout << "How many parcels need sending?" << endl;
cin >> iParcelCount;
do {
fCurrentPayload = 0;
do {
//Get parcel weight
cout << endl << endl << endl << "What is the weight the parcel " << iParcelLoaded << "?";
cin >> fParcelWeight;
//'Load' the parcel
cout << endl << endl << "Parcel loaded";
iParcelLoaded ++;
//Update the payload
fCurrentPayload = fCurrentPayload + fParcelWeight;
} while (((fCurrentPayload + fParcelWeight)) < fVanCapacity && iParcelLoaded < iParcelCount);
//Dispatch the van
cout << endl << endl << "Van dispatched.";
//Update the van count
iVanCount ++;
if (fCurrentPayload > fHeaviestVanWeight) {
//Update the heaviest weight
fHeaviestVanWeight = fCurrentPayload;
}
} while (iParcelLoaded <= iParcelCount);
cout << endl << endl << endl << "Vans dispatched: " << iVanCount;
cout << endl << endl << "Weight of heaviest van: " << fHeaviestVanWeight;
cout << endl << endl << endl << "Exit? Y for YES or N for NO." << endl;
cin >> cExit;
} while (cExit == 'N');
}