c++ output highest element in array - c++

I am trying to have the program output the winner in a candidate race when trying to go through the array to get the highest count instead of the highest it gets the next highest from zero, and i feel like i have tried everything.
I keep trying to change things around in the find winner function but nothing seems to be working I dont see what i am doing wrong please help.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
//User inputs data for candidates and votes.
//Output Candidates, votes, and percentage.
//Names that will be used are johnson, miller, duffy, robinson, ashtony
//count of votes to use = 5000, 4000, 6000, 2500, 1800, total 19300
//Percentages that will be used for candidates= 25.91, 20.73, 31.09, 12.95, 9.33
int findWinner(int votes[]);
void Results(string candidates[], int votes[]);
double Percentage(int votes[], int vote);
int tester[5] = {};
const int NUMBER_OF_CANDIDATES = 5;
int main()
{
string candidates[NUMBER_OF_CANDIDATES];
int votes[NUMBER_OF_CANDIDATES];
cout << "Enter 5 Candidates with their votes ex: DelBosque 7000: ";
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
cin >> candidates[i] >> votes[i];
}
cout << "Candidate Votes Received % of Total Votes" << endl;
Results(candidates, votes);
cout << "The Winner of the Election is " << candidates[findWinner(votes)] <<
endl;
return 0;
}
double Percentage(int votes[], int vote){
int sumOfVotes = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
sumOfVotes += votes[i];
}
double percent = static_cast<double>(vote) / sumOfVotes;
double votePercent = 0;
votePercent = percent * 100;
std::cout << std:: fixed;
std::cout << std:: setprecision(2);
std::cout << votePercent;
return 0;
};
void Results(string candidates[], int votes[]){
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
cout << candidates[i] << setw(15) << votes[i] << setw(15);
int percent = Percentage(votes, votes[i]);
cout << percent << "%" << endl;
};
};
// You are returning the number of votes. Shouldn't you be returning the
// index referenced by the highest number of votes?
int findWinner(int votes[]){
int index = 0;
int winner = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
if (votes[i] > winner)
winner = votes[i];
index = i;
};
return index;
};

You need both the following lines under the if condition.
winner = votes[i];
index = i;
like:
if (votes[i] > winner)
{
winner = votes[i];
index = i;
}
What you have is equivalent to:
if (votes[i] > winner)
{
winner = votes[i];
}
index = i;
which is not correct.

Related

Creating program that takes 5 grades from the user and finds the lowest grade, and then outputs average grade after dropping the lowest grade entered

`
#include <iostream>
#include <iomanip>
using namespace std;
void getGrades(double g[], const int SIZE)
{
cout << "Please enter " << SIZE << " grades:" << endl;
for(int i = 0; i < SIZE; i++)
{
cin >> g[i];
}
}
double getAverage(double g[], const int SIZE)
{
int total = 0;
for(int i = 0; i < SIZE; i++)
{
total += g[i];
}
return total/SIZE;
}
void findDropInfo(double g[], const int SIZE, int &lowest, double average)
{
int total = 0;
lowest = g[0];
for(int i = 1; i < SIZE; i++)
{
if (lowest > g[i]) {
lowest = g[i];
}
}
average = (total - lowest)/SIZE;
return average;
}
void printData(double g[], int lowest, double average, double avg_before)
{
cout << "The 5 grades entered by the user are:" << endl;
cout << g[];
cout << "Grade dropped: " << lowest << endl;
cout << "Final Average: " << average << endl;
cout << "Average before drop: " << avg_before << endl;
}
// TODO: Complete the function definitions
int main()
{
const int SIZE = 5;
double grades[SIZE];
int lowest;
double avg,
avgBeforeDrop;
// TODO: Add function calls
getGrades(grades[SIZE], SIZE);
getAverage(grades[SIZE], SIZE);
findDropInfo(grades[SIZE], SIZE, lowest, avg);
printData(grades[SIZE], lowest, avg, avgBeforeDrop);
return 0;
}
`
Whenever I run the program, I get multiple errors saying there's no matching candidate function. I'm not sure if the problems are in the functions themselves or in the function calls, but from what I know the functions themselves should be fine. I'm also told there's an expected expression in g[] but I' not sure what's wrong there either, as it's meant to be empty.
Most issues have already been resolved in the comments, but note: cout << g[] does not print the elements of g.
The way to do this is
char separator = /* the character you want to use to separate the printed elements of g */
for (int i = 0; i < SIZE; i++)
{
cout << g[i] << separator;
}
if (separator != '\n') cout << '\n'; //this is to put the next print on the next line
I would put this as a comment but I don't have enough reputation :|

Why isn't my array incrementing properly?

I am in a C++ class and I am having trouble with the project. The idea of the project is to create an ordering application using structs and arrays. As far as I can tell the program is working as intended except for the how many items of each item the person ordered part of my printMenu function. If I am mistaken and or you find more errors please let me know.
Here is the code:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
struct dinnerItemType
{
string dinnerItem;
double dinnerPrice;
int dinnerOrdered;
};
void getFood(dinnerItemType ourMenu[], int &size);
void printMenu(dinnerItemType ourMenu[], int size);
void printCheck(dinnerItemType ourMenu[], int size);
//Defines the global tax constant of 6%
const double TAX = 0.06;
int main()
{
dinnerItemType ourMenu[150];
int size = 0;
getFood(ourMenu, size);
printMenu(ourMenu, size);
printCheck(ourMenu, size);
system("pause");
return 0;
}
void getFood(dinnerItemType ourMenu[], int &size)
{
ourMenu[0].dinnerItem = "Chicken Sandwich";
ourMenu[0].dinnerPrice = 4.45;
ourMenu[0].dinnerOrdered = 0;
ourMenu[1].dinnerItem = "Fries";
ourMenu[1].dinnerPrice = 2.47;
ourMenu[1].dinnerOrdered = 0;
ourMenu[2].dinnerItem = "Truffle Fries";
ourMenu[2].dinnerPrice = 0.97;
ourMenu[2].dinnerOrdered = 0;
ourMenu[3].dinnerItem = "Filet 8oz";
ourMenu[3].dinnerPrice = 11.99;
ourMenu[3].dinnerOrdered = 0;
ourMenu[4].dinnerItem = "Fruit Basket";
ourMenu[4].dinnerPrice = 2.44;
ourMenu[4].dinnerOrdered = 0;
ourMenu[5].dinnerItem = "Tea";
ourMenu[5].dinnerPrice = 0.69;
ourMenu[5].dinnerOrdered = 0;
ourMenu[6].dinnerItem = "Water";
ourMenu[6].dinnerPrice = 0.25;
ourMenu[6].dinnerOrdered = 0;
size = 7;
}
void printMenu(dinnerItemType ourMenu[], int size)
{
int number;
int amount;
cout << "Welcome to the restraunt here are your menu items: \n";
for (int i = 0; i < size; i++)
{
cout << (i + 1) << ")";
cout << ourMenu[i].dinnerItem
<< "$"
<< ourMenu[i].dinnerPrice
<< endl;
}
cout << "To order just type in the number associated with the menu item and hit enter.\n"
<< "Once you have completed your order just type in 0 to go to checkout.\n";
cin >> number;
while (number != 0)
{
if (number >= 1 && number <= 8)
{
ourMenu[number - 1].dinnerOrdered++;
}
else
{
cout << "The number does not coorispond with a menu item please try again.\n";
}
cout << "To order just type in the number associated with the menu item and hit enter.\n"
<< "Once you have completed your order just type in 0 to go to checkout.\n";
cin >> number;
}
}
void printCheck(dinnerItemType ourMenu[], int size)
{
double total = 0;
cout << "Your Bill: ";
for (int i = 0; i < size; i++)
{
if (ourMenu[i].dinnerOrdered > 0)
{
total += ourMenu[i].dinnerPrice;
}
}
cout << "Tax: $ " << fixed << setprecision(2) << (total * TAX);
cout << " Ammount Due: $" << (total + (total * TAX)) << endl;
cout << "Thank you come again!" << endl;
}
This line:
total += ourMenu[i].dinnerPrice;
is only adding the cost of one meal to the total, regardless of how many times that meal is ordered.
To fix it: simply multiple the price by the number of times it is ordered:
total += ourMenu[i].dinnerPrice * ourMenu[i].dinnerOrdered;

(Pointers)Issue with calculating an average function after dropping a test score

When I enter the following value for each question it ask for the user input, the average is not correct. Values I enter are 3 for the amount of testscores, 64,90,52 for the score for each test score. My debugger shows 52 as my lowest drop test score so I do not believe the issue is the LowestTestScore function, but it's the calculate the average test score. The line below should give me the average of just only the two testscores (64,90). average =(total/size-1); // Average with the drop lowest test score is wrong If someone could guide me to the right direction I would gladly appreciated. I posted the entire source code because I was not sure if you could be able to figure out what is wrong with it with just snippets of the code. The sort function works as it should work, The main function works as it should as well. I believe the lowest function works too since it's giving me the correct output as my lowest testgrade.
#include <iostream>
void sortAscendingOrder(int*, int );
void LowestTestScore(int*, int);
void calculatesAverage(int*,int);
int main()
{
int* array = nullptr;
int input;
std::cout << "Enter the number of testscores you want to enter." <<std::endl;
std::cin >> input;
array = new int[input];
for(int count =0; count < input; count++)
{
std::cout << "Enter the test score" << (count +1) <<":" <<std::endl;
std::cin >> *(array+count);
while(*(array+count) < 0)
{
std::cout <<"You enter a negative number. Please enter a postive number." <<std::endl;
std::cin >> *(array+count);
}
}
sortAscendingOrder(array,input);
for(int count =0; count < input;count++)
{
std::cout << "\n" << *(array+count);
std::cout << std::endl;
}
LowestTestScore(array,input);
calculatesAverage(array,input);
return 0;
}
void sortAscendingOrder(int* input,int size)
{
int startScan,minIndex,minValue;
for(startScan =0; startScan < (size-1);startScan++)
{
minIndex = startScan;
minValue = *(input+startScan);
for(int index = startScan+1;index<size;index++)
{
if(*(input+index) < minValue)
{
minValue = *(input+index);
minIndex = index;
}
}
*(input+minIndex)=*(input+startScan);
*(input+startScan)=minValue;
}
}
void LowestTestScore(int* input, int size)
{
int count =0;
int* lowest = nullptr;
lowest = input;
for(count =1; count <size;count++)
{
if(*(input+count) < lowest[0])
{
lowest[0] = *(input+count);
}
}
std::cout << "Lowest score" << *lowest;
}
void calculatesAverage(int* input, int size)
{
int total = 0;
int average =0;
for(int count = 0; count < size; count++)
{
total += *(input+count);
}
average =(total/size-1); // Average with the drop lowest test score is wrong.
std::cout << "Your average is" << average;
}
To average after dropping the lowest test score, change
void LowestTestScore(int* input, int size)
{
int count =0;
int* lowest = nullptr;
lowest = input;
for(count =1; count <size;count++)
{
if(*(input+count) < lowest[0])
{
lowest[0] = *(input+count);
}
}
std::cout << "Lowest score" << *lowest;
}
To (notice '*lowest = 0;' at the bottom):
void LowestTestScore(int* input, int size)
{
int count =0;
int* lowest = nullptr;
lowest = input;
for(count =1; count <size;count++)
{
if(*(input+count) < lowest[0])
{
lowest[0] = *(input+count);
}
}
std::cout << "Lowest score" << *lowest;
*lowest = 0;
}
Then in your calculatesAverage function, make sure you calculate the average like:
average =(total/(size-1));

Cannot display proper percentage, or total from array in for loops

The problem I am having with my program is, first, when I calculate percent, it's not adding all the elements in the array to a total and diving them from. I tried putting the total += percents[i]; in a nested for-loop, but it just gave me negative %.
Also, my total at the end won't display anything. At first, I had it and all the function defined in the main(), but it didn't do anything. Even after the change, it doesn't work. Also, last thing, my file has 20 items, yet the loops only read in 19 items. If I change to 20, it crashes.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void inputValues(string names[], int votes[])
{
ifstream inputfile;
inputfile.open("votedata.txt");
if(inputfile.is_open())
{
for(int i = 0; i < 19; i++)
{
inputfile >> names[i] >> votes[i];
}
}
}
double *calcPercents( double percents[], int votes[], double total)
{
for(int i = 0; i < 19; i++)
{
percents[i] = votes[i];
total += percents[i];
percents[i] = (percents[i]/total)*100;
}
return percents;
}
string determineWinner(string names[], double percents[])
{
double temp = 0;
string winner;
for(int i = 0; i < 19; i++)
{
if(percents[i] > temp)
{
temp = percents[i];
winner = names[i];
}
}
return winner;
}
void displayResults(string names[], int votes[], double percents[])
{
int total = 0;
calcPercents(percents, votes, total);
cout << "Candidate Votes Received % of Total Votes " << endl;
for(int i = 0; i < 19; i++)
{
cout << names[i] << " " << votes[i] << " " << percents[i] << "%" << endl;
}
cout << "Total " << total << endl;
cout << " The winner of the election is " << determineWinner(names, percents) << endl;
}
int main()
{
string names[19], winner;
int votes[19];
double percents[19];
inputValues(names, votes);
displayResults(names, votes, percents);
}
My file is in the style:
bob (tab) 1254
joe (tab) 768
etc.
If you have to use arrays instead of std::vectors you should pass their size to the functions using them. One way is to set the size using a constant, like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std; // bad practice
const int size = 20;
void inputValues(string names[], int votes[], int n);
// add the size as a parameter of the function ^^^^
int calcPercents( double percents[], int votes[], int n );
//^^ I'll explain later why I changed your signature ^^^
string determineWinner(string names[], double percents[], int n );
void displayResults(string names[], int votes[], double percents[], int n);
int main()
{
// It's always better to initialize the variables to avoid undefined behavior
// like the negative percentages you have noticed
string names[size] ="";
int votes[size] = {0};
double percents[size] = {0.0};
inputValues(names, votes, size);
displayResults(names, votes, percents, size);
}
To calculate the percentages you can use two loops, one for the sum and the other to get the percentage. In your function you pass total as a parameter by value, so it will be copied and the changes will never be visible outside the function. I choose to return that vaule, even if doing so the name of function becomes a litle misleading:
int calcPercents( double percents[], int votes[], int n )
{
int total = 0;
for(int i = 0; i < n; i++)
// note the bound ^^^
{
total += votes[i];
}
double factor = 100.0 / total;
for(int i = 0; i < n; i++)
{
percents[i] = factor * votes[i];
}
return total;
}
You should also add some checks to the input function, I only add the size parameter. Note that having initialized the arrays, even if it fails reading the file the arrays doesn't contain random values:
void inputValues(string names[], int votes[], int n)
{
ifstream inputfile;
inputfile.open("votedata.txt");
if(inputfile.is_open())
{
for(int i = 0; i < n; i++)
{
inputfile >> names[i] >> votes[i];
}
}
}
I'd change the function which determine the winner too:
string determineWinner(string names[], double percents[], int n )
{
if ( !n )
{
return "";
}
double max = percents[0];
// update an index instead of a string
int winner = 0;
for( int i = 1; i < n; i++ )
{
if( percents[i] > max )
{
max = percents[i];
winner = i;
}
}
return names[winner];
}
For the last function, only remember to add the size:
void displayResults(string names[], int votes[], double percents[], int n)
{
int total = calcPercents(percents, votes, n);
cout << "Candidate Votes Received % of Total Votes " << endl;
for( int i = 0; i < n; i++ )
{
cout << names[i] << " " << votes[i] << " "
<< percents[i] << "%" << endl;
}
cout << "Total " << total << endl;
cout << " The winner of the election is "
<< determineWinner(names, percents,n) << endl;
}

Chips and Salsa using header file

Revise Programming Challenge 3 to use an array of Product objects instad of two parallel arrays. The Product class will need member variables to hold a product name and a quantity.
Challenge 3: Write a program that lets a maker of chips and salsa keep track of their sales for five different types of salsa they produce: mild, medium, sweet, hot, and zesty. It should use two parallel five-element arrays: an array of strings that holds five salsa names and an array of integers that holds the number of jars sold during the past month for each salsa type. The salsa names should be stored using an initialization list at the time the name array is created. The program should prompt the user to enter the number of jars sold for each type. One this sales data has been entered, the program should produce a report that displays sales for each salsa type, total sales, and the names of the highest selling and lowest selling products.
I did Challenge 3, code here.
After much trying, I can't seem to get said program to work. I've commented the errors, and what they are. Here's what I've got so far:
#ifndef SALSA_H
#define SALSA_H
class Salsa
{
private:
void getTotal();
void getHigh();
void getLow();
int count;
int total;
int high;
int low;
int flavor;
public:
void getSold();
};
#endif
#include "Salsa.h"
#include <iostream>
#include <string>
using namespace std;
void Salsa::getSold()
{
for (count = 0; count < 5; count++)
{
cout << "Jar sold last month of ";
cout << count + 1;
cin >> flavor[count]; //Get error saying subscript array or pointer type
while (flavor[count] <= 0) // Get error saying subscript array or pointer type
cout << "Jars sold must be greater than or equal to 0.";
cout << "Re-enter jars sold for last month ";
cin >> flavor[count];
cout << endl;
}
}
Salsa::getTotal();
Salsa::getHigh();
Salsa::getLow();
}
void Salsa::getTotal()
total = 0;
for (count = 0; count < 5; count++)
total += flavor[count];
cout << "Total Sales: " << total << endl;
}
void Salsa::getHigh()
{
highest = flavor[0];
int index = 1;
for (count = 0; count < 5; count++)
if (flavor[count] > highest)
{
highest = flavor[count];
index = count + 1;
}
cout << "High Seller: " << flavor << endl;
}
void Salsa::getLow()
{
lowest = flavor[0];
int index = 1;
for (count = 0; count < 5; count++)
if (flavor[count] < lowest)
{
lowest = flavor[count];
index = count + 1;
}
cout << "Low Seller: " << flavor << endl;
}
#include "Salsa.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int SALS_FLAV = 5;
string flavor[SALS_FLAV] = { "mild", "medium", "sweet", "hot", "zesty" };
Salsa sold;
for (int index = 0; index < SALS_FLAV; index++)
getSold(flavor[SALS_FLAV]); // Get error saying 'getSold' identifier not found
sold.getSold();
return 0;
}
There are many issues with your code. The following code may do what you want.
You should study it and try to improve it. One such improvement could be the use of std::vector as opposed to arrays. This will mean you can avoid manual memory management (new/delete) and therefore achieve the ideal of not having to define a destructor.
#include <iostream>
#include <string>
using namespace std;
class Salsa
{
public:
Salsa(string* flavours, int num_flavours);
~Salsa();
void getSold();
private:
void getTotal();
void getHigh();
void getLow();
string* flavours_;
int num_flavours_;
int* sold_count_;
};
Salsa::Salsa(string* flavours, int num_flavours)
{
num_flavours_ = num_flavours;
flavours_ = new string[num_flavours_];
sold_count_ = new int[num_flavours_];
int i;
for(i = 0; i < num_flavours_; i++)
{
flavours_[i] = flavours[i];
}
}
Salsa::~Salsa()
{
delete[] flavours_;
delete[] sold_count_;
}
void Salsa::getSold()
{
int count;
int num;
for (count = 0; count < num_flavours_; count++)
{
cout << "Jar sold last month of " << flavours_[count] << " ";
cin >> num;
while(num <= 0)
{
cout << "Jars sold must be greater than or equal to 0." << endl;
cout << "Re-enter jars sold for last month " << endl;
cin >> num;
}
sold_count_[count] = num;
}
getTotal();
getHigh();
getLow();
}
void Salsa::getTotal()
{
int count;
int total = 0;
for (count = 0; count < num_flavours_; count++)
total += sold_count_[count];
cout << "Total Sales: " << total << endl;
}
void Salsa::getHigh()
{
int count;
int highest = sold_count_[0];
int index = 0;
for (count = 0; count < num_flavours_; count++)
{
if (sold_count_[count] > highest)
{
highest = sold_count_[count];
index = count;
}
}
cout << "High Seller: " << flavours_[index] << endl;
}
void Salsa::getLow()
{
int count;
int lowest = sold_count_[0];
int index = 0;
for (count = 0; count < num_flavours_; count++)
{
if (sold_count_[count] < lowest)
{
lowest = sold_count_[count];
index = count;
}
}
cout << "Low Seller: " << flavours_[index] << endl;
}
int main()
{
const int SALS_FLAV = 5;
string flavor[SALS_FLAV] = { "mild", "medium", "sweet", "hot", "zesty" };
Salsa sold(flavor, SALS_FLAV);
sold.getSold();
return 0;
}