c++ sorting array function - c++

double gross_pay(double pay[7]){
int i;
double add;
add = 0;
for(i = 0; i < 7; i++){
add += pay[i];
}
return add;
}
int find_lowest(double pay[7]){
double lowest;
int index, i;
index = 0;
lowest = pay[0];
for(i = 1; i < 7; i++){
if(pay[i] < lowest){
index = i;
lowest = pay[i];
}
}
return index;
}
int find_highest(double pay[7]){
double highest;
int index, i;
index = 0;
highest = pay[0];
for(i = 1; i < 7; i++){
if(pay[i] > highest){
index = i;
highest = pay[i];
}
}
return index;
}
int main()
{
string dayweek[7];
double dailypay[7];
int i;
double pay, add;
int lowest, highest;
dayweek[0] = "Monday";
dayweek[1] = "Tuesday";
dayweek[2] = "Wednesday";
dayweek[3] = "Thursday";
dayweek[4] = "Friday";
dayweek[5] = "Saturday";
dayweek[6] = "Sunday";
for(i = 0; i < 7; i++){
cout << "Please enter the gross sales ecieved on" << endl;
cout << dayweek[i] << ": ";
cin >> pay;
dailypay[i] = pay;
cout << endl << endl;
}
add = gross_pay(dailypay);
lowest = find_lowest(dailypay);
highest = find_highest(dailypay);
cout << endl;
cout << "Total sales for the week: " << "$" << add << endl << endl;
cout << "Total taxes withheld: $" << add*.0975 << "\n\n";
cout << "Net profit: $" << add*.9025 <<"\n\n";
cout << "Day with the highest sales amount was" << endl;
cout << dayweek[highest].c_str() <<" with a sales total of $" << dailypay[highest];
cout << "\n\nDay with the lowest sales amount was" << endl;
cout << dayweek[lowest].c_str() << " with a sales total of $" << dailypay[lowest];
return 0;
}
cant seem to figure out the code that will sort the array in order from lowest to highest for example
Sales sorted from lowest to highest:
Monday had gross sales of $101.00
Tuesday had gross sales of $135.64
Sunday had gross sales of $245.55
Wednesday had gross sales of $533.44
Thursday had gross sales of $922.42
Saturday had gross sales of $1555.22
Friday had gross sales of $2242.63
those are also the input values for gross sales,
this is my first time asking a question on this site, if i did anything wrong please let me know,thanks for all the help !
could you write one using this
void sortArray(double arySales[], int size, string aryDays[])
{
bool swap;
double tempSales;
string tempDays;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (arySales[count] > arySales[count + 1])
{
tempSales = arySales[count];
arySales[count] = arySales[count + 1];
arySales[count + 1] = tempSales;
tempDays = aryDays[count];
aryDays[count] = aryDays[count + 1];
aryDays[count + 1] = tempDays;
swap = true;
}
}
} while (swap);
}

You should put the day-of-week index (0 to 6) plus the value for that day into a struct, and then populate a std::vector of these structs. Then you can sort them easily:
struct PayForDay {
int day; // 0..6
double pay;
};
bool PayLess(const PayForDay& lhs, const PayForDay& rhs) {
return lhs.pay < rhs.pay;
}
std::vector<PayForDay> payments;
std::sort(payments.begin(), payments.end(), PayLess);

Related

Your C++ program must use functions to input the scores, compute the average, and find the index of the highest score

I've been working on this for hours now and I'm almost done. I can't get the program to display the correct student ID.
Also the "highIndex" function is suppose to be an "int" but I started with a double. When I try to change it, everything else seems to fall apart.
How do I get the high score to be associated with the student ID so I can output it correctly? I also need to highIndex to be an int which means some other things needs to be changed.
Any help would be much appreciated :)
Here's what I have so far
void inputAnswers(int studentIds[], double scores[]);
double getAverage(double scores[])
{
double total = 0;
for (int count = 0; count <= 6; count++)
{
total += scores[count];
}
return total / 7;
}
double highIndex(double score[])
{
double highScore = score[0];
double indexHigh = 1;
for (int count = 0; count <= 6; count++)
{
if (score[count] > highScore)
{
highScore = score[count];
indexHigh = count;
}
}
return highScore;
}
int main()
{
const int ids = 7;
int student[ids] = { 1234, 2333, 4432, 3323, 2143, 3425, 4123 };
double scores[7];
double highScore[7];
// Gets the test score from user
inputAnswers(student, scores);
// Calculates the average
cout << "The average score is " << getAverage(scores) << endl;
// Calculates highest score
cout << "The high score was student " << highIndex(highScore) << " with a score of " << highIndex(scores);
return 0;
}
// Function gets student scores
void inputAnswers(int student[], double scores[])
{
for (int count = 0; count <= 6; count++)
{
cout << "Enter the score for student "<< student[count] << ": ";
cin >> scores[count];
}
}
As per my observation you haven't supplied any values to the Highscore array and it is not required as well.
If all you need is to find average score, highscore and id of student with highscore this slight change will do the trick just adjusted 3 values from your code and is documented at corresponding lines.
#include<iostream>
using namespace std;
double getAverage(double scores[])
{
double total = 0;
for (int count = 0; count <= 6; count++)
{
total += scores[count];
}
return total / 7;
}
void inputAnswers(int student[], double scores[])
{
for (int count = 0; count <= 6; count++)
{
cout << "Enter the score for student "<< student[count] << ": ";
cin >> scores[count];
}
}
int highIndex(double score[])
{
double highScore = score[0];
double indexHigh = 0; //as we are assigning from position 0
for (int count = 1; count <= 6; count++)
{
if (score[count] > highScore)
{
highScore = score[count];
indexHigh = count;
}
}
return indexHigh; //returns index of highscore
}
int main()
{
const int ids = 7;
int student[ids] = { 1234, 2333, 4432, 3323, 2143, 3425, 4123 };
double scores[7];
//double highScore[7]; no need
// Gets the test score from user
inputAnswers(student, scores);
// Calculates the average
cout << "The average score is " << getAverage(scores) << endl;
// Calculates highest score
cout << "The high score was student " << student[highIndex(scores)] << " with a score of " << scores[highIndex(scores)]; //uses returned index to find values from array
return 0;
}
Although i strongly recommend using class or structures for such data collection of any entitiy. Happy Coding :-)

Cannot convert int to int[][]

I am doing a a problem using Multi-dimensional Arrays. I call the function in main but I get this Error message. This is the Original Problem I have:
A local zoo wants to keep track of how many pounds of food each of its three tigers eats each day during
a typical week. Write a program that stores this information in a two-dimensional 3 x 7 array, where
each row represents a different tiger and each column represents a different day of the week. The
program should first have the user input the data for each tiger. Then it should create a report that
includes the following information:
Average amount of food eaten by each of the tigers during the week.
Average amount of food eaten by all the tigers per day for each day.
The least amount of food eaten during the week by any tiger.
The greatest amount of food eaten during the week by any tiger.
the code:
#include <iostream>
using namespace std;
const int TIGERS = 3;
const int DAYS = 7;
int food[TIGERS][DAYS];
void inputArray(int food[TIGERS][DAYS]);
float AvgTig(float);
float Least(float);
float most(float);
int main()
{
float maximum;
float minimum;
float total = 0.0f;
float average = 0.0f;
float result = 0;
inputArray(food);
maximum = food[0][0];
minimum = food[0][0];
cout << "\n \n";
AvgTig(result);
cout << "\n \n";
Least(minimum);
cout << "\n \n";
most(maximum);
cout << "\n \n";
system("PAUSE");
return 0;
//end program
}
void inputArray(int food[TIGERS][DAYS])
{
int total = 0;
for (int tig = 0; tig < TIGERS; tig++) {
for (int day = 0; day < DAYS; day++) {
cout << "TIGER " << (day + 1) << ", day " << (day + 1) << ": ";
cin >> food[tig][day];
}
cout << endl;
}
}
float AvgTig(float output)
{
int total = 0;
for (int i = 0; i < TIGERS; i++) {
for (int day = 0; day < DAYS; day++) {
total += food[i][day];
}
cout << endl;
}
output = total / (TIGERS * DAYS);
cout << "Average food for Tigers in the days is :" << output << " ";
return output;
}
float Least(float minimum)
{
for (int least = 0; least < TIGERS; least++) {
for (int day = 0; day < DAYS; day++) {
if (food[least][day] < minimum)
minimum = food[least][day];
}
}
cout << "Minimum food eaten: " << minimum << " ";
return minimum;
}
float most(float maximum)
{
for (int most = 0; most < TIGERS; most++) {
for (int day = 0; day < DAYS; day++) {
if (food[most][day] > maximum)
maximum = food[most][day];
}
}
cout << " Maximum number of food is: " << maximum << " ";
return maximum;
}
On this line:
inputArray(food[TIGERS][DAYS]);
in main, you are calling inputArray with a single int, and not the entire food array. In fact, even reading this position in food is UB.
You need to call the function like this:
inputArray(food);

Double variable outputs 32767 always instead of user input

I'm writing code that asks about rainfall each month, then outputs yearly total, monthly average, min, and max rain month (index). My code is almost complete, except that instead of outputting the max value the output always shows the max range of the variable type 32767 (e.g. if rain is 70mm and maximum, console shows 32767 always). Thanks for your help. I'm self-learning.
I have tried the following code.
#include<iostream>
using namespace std;
int main(){
const int numMonths = 3;
double monthlyRain[numMonths]={0,0,0};
string monthName[numMonths]= {"Jan", "Feb", "Mar"};
int count = 0;
int indexWettest = 0;
int indexDriest = 0;
double yearTotal=0, monthlyAverage=0;
double monthHighest;
double monthLowest;
monthLowest = monthlyRain[0];
monthHighest = monthlyRain[0];
// enter monthly rain;
for (int count=0; count < numMonths; count++){
cout << "Please enter amount of rain in " << monthName[count] << endl;
cin >> monthlyRain[count];
}
// print month and corresponding rain amount;
cout << "Month --- Rain(mm)" << endl;
for (int count = 0; count < numMonths; count++){
cout << monthName[count] << " " << monthlyRain[count] << endl;
}
// calculate year total;
for (int count = 0; count < numMonths; count++){
yearTotal += monthlyRain[count];
}
// calculate average monthly rainfall;
monthlyAverage = yearTotal/numMonths;
// find month with lowest rainfall;
// find month with highest rainfall;
for (int count = 0; count < numMonths; count++){
if (monthlyRain[count] > monthHighest){
monthHighest = monthlyRain[count+1];
indexWettest = count;
}
}
// PROBLEM IS HERE!;
for (int count = 0; count < numMonths; count++){
if (monthlyRain[count] < monthLowest){
monthLowest = monthlyRain[count];
indexDriest = count;
}
}
cout << "Total yearly rain fall is: " << yearTotal << endl;
cout << "Average monthly rainfall is: " << monthlyAverage << endl;
cout << "The driest month is " << monthName[indexDriest] << " with rain amount of " << monthLowest << endl;
cout << "The wettest month is " << monthName[indexWettest] << " with rain amount of " << monthHighest << endl; //<< monthName[indexWettest];
return 0;
}
Expected result is the user input.
Read compiler warnings.
main.cpp:35:19: warning: 'yearTotal' may be used uninitialized in this function [-
Wmaybe-uninitialized]
yearTotal += monthlyRain[count];
Line that declares yearTotal should be double yearTotal = 0;
Same with other variables. Always initialize them.

Printing a receipt using parallel arrays c++

I have been given this assignment for a lab project, and I have everything working until it gets to the receipt part. The issues I am having are 1) printing the incorrect menu items ordered, and 2) getting -42........ number for the pricing. I've looked through this several times and have spoken with others in the class. This is where we are ALL having issues. My TA said to use array[array1[counter]] for this section, but it doesn't seem to work. Can you help me focus on where things are seriously incorrect?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const int NUM_MENU_ITEMS = 10; // num items on the menu
const int MAX_ORDER_ITEMS = 5; // max num of items per order
const double DISCOUNT_MIN = 20.00; // min subtotal to get discount
const double DISCOUNT_RATE = 0.25; // disc rate for highest-priced item
// Menu: parallel constant arrays
const string menuItem[NUM_MENU_ITEMS] = {
"Burger", "Hot Dog", "Chicken Fingers", "Fries",
"Tots", "Tea", "Coke", "Diet Coke", "Water", "Cookies" };
const double menuPrice[NUM_MENU_ITEMS] = {
3.50, 2.75, 4.25, 2.50, 3.25,
1.00, 1.25, 1.25, 0.25, 2.50 };
int main()
{
// Order: parallel partial arrays of items ordered
// Each item has an item number, quantity ordered, and total price
// TODO: declare a list of item numbers
// TODO: declare a list of quantities
// TODO: declare a list of item prices (menu price X quantity)
// TODO: declare other variables as needed
double total, subtotal, discount;
// receipt line data
string recName;
int recQty;
int j = 0;
double recPrice;
// print menu
cout << "MENU:\n" << fixed << setprecision(2);
cout << "## Item Price\n";
cout << "-- --------------- -------\n";
// TODO: write a loop to print the menu
int i = 0;
int itemNumber[NUM_MENU_ITEMS] = {
0,1, 2, 3, 4, 5, 6, 7, 8, 9 };
while (i <= 9)
{
cout << setw(2) << itemNumber[i] << " " <<
left << setw(15) << menuItem[i] <<
right << " $ " << setw(5) << menuPrice[i] << endl;
i++;
}
cout << endl;
// get order
int counter = 0;
int itemQuantity[MAX_ORDER_ITEMS];
double itemPrice[MAX_ORDER_ITEMS];
int itemOrder[MAX_ORDER_ITEMS];
string itemName[MAX_ORDER_ITEMS];
do {
cout << "Enter quantity and menu item number (0 0 to end):\n";
cout << "Item 0: ";
cin >> itemQuantity[counter] >> itemOrder[counter];
itemOrder[counter] = itemNumber[counter];
itemPrice[counter] = menuPrice[itemOrder[counter]] *
itemQuantity[counter];
itemName[counter] = menuItem[itemOrder[counter]];
counter++;
} while (counter < MAX_ORDER_ITEMS && itemQuantity[counter] != 0);
// TODO: repeat inputs until quantity is 0 or MAX_ORDER_ITEMS exceeded
//{
// //TODO: add an item to the order parallel arrays
// cout << "Item " << menuItem[i] << ": ";
// cin >> itemQuantity[i] >> itemPrice[i];
//}
double maxItemPrice = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
if (itemPrice[counter] > maxItemPrice)
maxItemPrice = i;
}
// find the subtotal price
// TODO: use a loop to calculate the sum of all order prices
subtotal = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
subtotal = subtotal + itemPrice[counter];
}
// discount highest order line by 25% when total > $20
if (subtotal >= DISCOUNT_MIN)
{
// TODO: add a loop to find the maximum item price
discount = DISCOUNT_RATE * maxItemPrice;
}
else
discount = 0;
// calculate the total price
total = subtotal - discount;
// print the receipt
cout << "\n----------------------------\n";
cout << "Item Qty Price\n";
cout << "--------------- --- -------\n";
// TODO: use a loop to print the lines of the receipt
i = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
recName = itemName[i];
recQty = itemQuantity[i];
recPrice = itemPrice[menuPrice[i]];
cout << left << setw(15) << recName << " "
<< right << setw(3) << recQty << " $"
<< setw(6) << recPrice << endl;
}
cout << "\nSubtotal: $" << setw(6) << subtotal << endl;
cout << "Discount: $" << setw(6) << discount << endl;
cout << "Total Price: $" << setw(6) << total << endl << endl;
system("pause");
return 0;
}
In this line in the do while loop:
} while (counter < MAX_ORDER_ITEMS && itemQuantity[counter] != 0);
you have already incremented counter so your while loop is checking a part of the
itemQuantity
array that has not been input yet.
Also, here
double maxItemPrice = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
if (itemPrice[counter] > maxItemPrice)
maxItemPrice = i;
}
counter is a variable used previously and has not been updated. What is counter representing, and what is i?
And again here,
subtotal = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
subtotal = subtotal + itemPrice[counter];
}
Counter is still the same as it was left in the do while loop. Here it should be
subtotal = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
subtotal = subtotal + itemPrice[i];
}
Check array parameters closely and make sure what's written is doing what you want it to do. Best of luck!

Using the 3rd parameter of a function

Can anyone help me figure out how to get the 3rd parameter of the getLowest/getHighest function to reference the names array that has the months of the year and display the names of the month when I call for it? What's supposed to happen with those functions is that they are supposed to be able to give the name of the month that corresponds with the lowest/highest amount in the array. I can't seem to get it down. That's the last thing I need for this code and I'm trying very hard to figure it out. Any help would be much appreciated. Thank you.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//Function prototypes
double getTotal(double [], int);
double getAverage(double [], int);
double getLowest(double [], int, int&);
double getHighest(double [], int, int&);
int main()
{
const int months = 12;
string names[months] = { "January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December" };
double rainfall[months];
double total, average, maxRain, minRain;
int indexofLowest, indexofHighest;
//Input from using for the rainfall amounts
std::cout << "Please enter the amount of rainfall in inches, that fell in each month.\n";
std::cout << "Enter the amount of rainfall for " << names[0];
std::cin >> rainfall[0];
std::cout << "Enter the amount of rainfall for " << names[1];
std::cin >> rainfall[1];
std::cout << "Enter the amount of rainfall for " << names[2];
std::cin >> rainfall[2];
std::cout << "Enter the amount of rainfall for " << names[3];
std::cin >> rainfall[3];
std::cout << "Enter the amount of rainfall for " << names[4];
std::cin >> rainfall[4];
std::cout << "Enter the amount of rainfall for " << names[5];
std::cin >> rainfall[5];
std::cout << "Enter the amount of rainfall for " << names[6];
std::cin >> rainfall[6];
std::cout << "Enter the amount of rainfall for " << names[7];
std::cin >> rainfall[7];
std::cout << "Enter the amount of rainfall for " << names[8];
std::cin >> rainfall[8];
std::cout << "Enter the amount of rainfall for " << names[9];
std::cin >> rainfall[9];
std::cout << "Enter the amount of rainfall for " << names[10];
std::cin >> rainfall[10];
std::cout << "Enter the amount of rainfall for " << names[11];
std::cin >> rainfall[11];
//Get total
total = getTotal(rainfall, months);
//Get average
average = getAverage(rainfall, months);
//Get the max amount of rain
maxRain = getHighest(rainfall, months, indexofHighest);
//Get the min amount of rain
minRain = getLowest(rainfall, months, indexofLowest);
//Display the total, average, highest/lowest
std::cout << "The total amount of rain for the year is " << total << " inches.\n";
std::cout << "The average amount of rain monthly is " << average << " inches per month.\n";
std::cout << "The month that had the highest amount of rainfall is " << names[indexofHighest] << " with " << maxRain << " inches.\n";
std::cout << "The month that has the lowest amount of rainfall is " << names[indexofLowest] << " with " << minRain << " inches.\n";
return 0;
}
//Definition of function getTotal
double getTotal(double rainfall[], int months)
{
double total = 0;
for (int count = 0; count < months; count++)
{
total += rainfall[count];
}
return total;
}
//Definition of function getAverage
double getAverage(double rainfall[], int months)
{
double total = 0;
double average = 0.0;
for (int count = 0; count < months; count++)
{
total += rainfall[count];
average = total / months;
}
return average;
}
//Defintion of function getLowest
double getLowest(double rainfall[], int months, int indexofLowest)
{
int count;
double lowest;
lowest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[count] < lowest)
lowest = rainfall[count];
}
return lowest;
}
//Definition of function getHighest
double getHighest(double rainfall[], int months, int indexofHighest)
{
int count;
double highest;
highest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[0] > highest)
highest = rainfall[count];
}
return highest;
}
I tried your code. You have a few bugs. I guess you need to try harder in the future. Anyways here is a working solution with minimal changes to your existing code -
//Defintion of function getLowest
double getLowest(double rainfall[], int months, int & indexofLowest)
{
int count;
double lowest;
lowest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[count] < lowest)
{
lowest = rainfall[count];
indexofLowest = count;
}
}
return lowest;
}
//Definition of function getHighest
double getHighest(double rainfall[], int months, int & indexofHighest)
{
int count;
double highest;
highest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[count] > highest)
{
highest = rainfall[count];
indexofHighest = count;
}
}
return highest;
}
You have to set indexofLowest and indexofHighest in your functions (and match their prototype):
//Defintion of function getLowest
double getLowest(double rainfall[], int months, int& indexofLowest)
int count;
double lowest;
lowest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[count] < lowest) {
lowest = rainfall[count];
indexofLowest = count;
}
}
return lowest;
}
//Definition of function getHighest
double getHighest(double rainfall[], int months, int& indexofHighest)
{
int count;
double highest;
highest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[count] > highest) { //there was a bug here in your code: ... rainfall[0]
highest = rainfall[count];
indexofHeighest = count;
}
}
return highest;
}
you can also use a function to input data (and maybe add a little error checking):
//Input from using for the rainfall amounts
int readData(string monthNames[], double rain[], int n) {
int i;
std::cout << "Please enter the amount of rainfall in inches, that fell in each month.\n";
for ( i=0; i<n; i++) {
std::cout << "Enter the amount of rainfall for " << monthNames[i];
std::cin >> rain[i]; //check this value somehow!
}
return i;
}