currently stuck on a homework problem and hoping for some hints as to why my code isn't working / what I'm missing. The homework question asks you to make an array that holds a string of salsa flavors for a store, gathers data from the user input on how many were sold (jars) and then display the total sales from each flavor sold. Ive got all that down, but the question goes on to ask you to retrieve the best seller and the worst seller. I've attempted and can get my code to pull two flavors, but they're completely incorrect. Any help is appreciated! Here is my code:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// variables
const int SIZE = 5;
string salsas[SIZE] = { "Mild", "Medium", "Sweet", "Hot", "Zesty"};
//names of salsas
int jars[SIZE]; //holds number of jars user enters
int sales[SIZE]; //holds sales numbers
int count; //counts for a loop
int largest; //largest sale
int smallest; //smallest sale
cout << "Enter the monthly number of jars sold for each type of
salsa.\n\n";
// Display the salsas in the array
for (int count = 0; count < SIZE; count++)
{
cout << salsas[count] << ": ";
cin >> jars[count];
}
// Display salsa sales
cout << "\nEach jar of salsa, no matter the type, costs $5.50.\n";
cout << "Here are the monthly sales numbers for each type of salsa.
\n\n";
cout << fixed << showpoint << setprecision(2);
for (int count = 0; count < SIZE; count++)
{
double sales = jars[count] * 5.50;
cout << salsas[count] << ": $";
cout << sales << endl;
}
//Gets highest sale
{
int count;
int largest = sales[0];
int index = 0;
for (count = 0; count < SIZE; count++)
{
if (sales[count] > largest)
{
largest = sales[count];
index = count;
}
}
cout << "\nBest Seller: " << salsas[index] << endl;
}
//Gets lowest sale
{
int count;
int smallest = sales[0];
int index = 0;
for (count = 0; count < SIZE; count++)
{
if (sales[count] < smallest)
{
smallest = sales[count];
index = count;
}
}
cout << "\nWorst Seller: " << salsas[index] << endl;
}
return 0;
}
One of the biggest hindrances in debugging your own code is in naming your variables. If you've declared count, largest, and smallest variables at the start of your main() function but you redeclare them in a separate block later on. It's downright redundant.
The actual bug is that you're not actually calculating and filling your sales[] array. Comparing them later on for largest and smallest wouldn't work as intended.
Look for this line in the code below
sales[count] = jars[count] * 5.50;
Lé Code
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// variables
const int SIZE = 5;
string salsas[SIZE] = { "Mild", "Medium", "Sweet", "Hot", "Zesty"};
//names of salsas
int jars[SIZE]; //holds number of jars user enters
int sales[SIZE]; //holds sales numbers
// int count; //counts for a loop // no need
// int largest; //largest sale // no need
// int smallest; //smallest sale // no need
cout << "Enter the monthly number of jars sold for each type of salsa.\n\n";
// Display the salsas in the array
for (int count = 0; count < SIZE; count++)
{
cout << salsas[count] << ": ";
cin >> jars[count];
}
// Display salsa sales
cout << "\nEach jar of salsa, no matter the type, costs $5.50.\n";
cout << "Here are the monthly sales numbers for each type of salsa. \n\n";
cout << fixed << showpoint << setprecision(2);
for (int count = 0; count < SIZE; count++) // declare `count` where it is used
{
sales[count] = jars[count] * 5.50; // calculate sales[count] IMPORTANT
cout << salsas[count] << ": $";
cout << sales[count] << endl; // show appropriate output
}
//Gets highest sale
int largest = sales[0]; // declare largest and index closest to where they are used
int index = 0;
for (int count = 0; count < SIZE; count++)
{
if (sales[count] > largest)
{
largest = sales[count];
index = count;
}
}
cout << "\nBest Seller: " << salsas[index] << endl;
//Gets lowest sale
int smallest = sales[0]; // declare smallest closest to where it is used
index = 0; // reuse your old variable
for (int count = 0; count < SIZE; count++)
{
if (sales[count] < smallest)
{
smallest = sales[count];
index = count;
}
}
cout << "\nWorst Seller: " << salsas[index] << endl;
return 0;
}
Sample Console Interaction
Enter the monthly number of jars sold for each type of salsa.
Mild: 20
Medium: 10
Sweet: 5
Hot: 2
Zesty: 1
Each jar of salsa, no matter the type, costs $5.50.
Here are the monthly sales numbers for each type of salsa.
Mild: $110
Medium: $55
Sweet: $27
Hot: $11
Zesty: $5
Best Seller: Mild
Worst Seller: Zesty
Related
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 :-)
I'm trying to use two parallel arrays to find which jar of salsa sold the most and sold the least. I'm trying to output the highest and lowest sales number to later turn into a salsa name to display. However, my two void functions keep producing garbage output and I can't figure out why because I used this same algorithm with another programming question yesterday. Also, does anyone have any suggestions in how I can get my sales numbers to output in a straight vertical line? I tried using 'right' and 'setw(30)' but that didn't help much, thank you for your time.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void smallest(string[], int[]);
void biggest(string[], int[]);
int main()
{
const int size = 5;
string name[size] = { "mild", "medium", "sweet", "hot", "zesty"};
int sales[size];
int total = 0;
for (int i = 0; i < size; i++)
{
cout << "Enter the amount of jars of " << name[i] << " salsa that were sold: ";
cin >> sales[i];
while (sales[i] < 0)
{
cout << "Invalid Input! Enter a positive amount of jars of " << name[i] << " salsa that were sold: ";
cin >> sales[i];
}
}
cout << "Salsa Type Amount Sold\n";
cout << "===============================\n";
for (int i = 0; i < size; i++)
{
cout << name[i] << setw(30) << right << sales[i] << endl;
}
for (int i = 0; i < size; i++)
{
total = total + sales[i];
}
cout << "\nThe total sales of jars is: " << total << endl;
smallest(name, sales);
biggest(name, sales);
}
void smallest(string name[], int sales[])
{
int i;
int lowest;
lowest = sales[0];
for (i = 1; i < 5; i++)
{
if (sales[i] < lowest)
{
lowest = sales[i];
}
}cout << "The lowest selling product is: " << sales[i] << endl;
}
void biggest(string name[], int sales[])
{
int i;
int highest;
highest = sales[0];
for (i = 1; i < 5; i++)
{
if (sales[i] > highest)
{
highest = sales[i];
}
}cout << "The highest selling product is: " << sales[i] << endl;
}
You are not printing out the lowest and highest with these lines of code:
cout << "The lowest selling product is: " << sales[i] << endl;
//...
cout << "The highest selling product is: " << sales[i] << endl;
Instead you are printing the value of sales[5], since i == 5. That is an out-of-bounds access, thus the reason for the garbage value (actually, accessing an element out-of-bounds is undefined behavior).
You should be printing whatever the values are at index lowest and highest, not i:
Example:
cout << "The lowest selling product is: " << name[lowest] << endl;
//...
cout << "The highest selling product is: " << name[highest] << endl;
You could have prevented this error by not declaring the loop index i outside the for loop, and instead declare it within the initialization portion of the for loop syntax:
void smallest(string name[], int sales[])
{
int lowest;
lowest = sales[0];
for (int i = 1; i < 5; i++)
{
if (sales[i] < lowest)
{
lowest = sales[i];
}
}
cout << "The lowest selling product is: " << sales[i] << endl; // <-- Compiler error
}
Doing that would have stopped the sales[i] from compiling, since i would be local to the for loop.
Edit:
To print out the lowest and highest names, you should instead figure out the index of the highest and lowest. Then use the index in the final print statement. The code shown above was not completed, but here is an example:
void smallest(string name[], int sales[])
{
int lowest = sales[0];
int lowestIndex = 0;
for (int i = 1; i < 5; i++)
{
if (sales[i] < lowest)
{
lowest = sales[i];
lowestIndex = i
}
}
cout << "The lowest selling product is: " << name[lowestIndex] << endl;
cout << "The lowest selling price is: " << sales[lowestIndex] << endl;
However, using C++ library functions std::min_element and std::distance, you can get the lowest index with two function calls:
#include <algorithm>
//...
void smallest(string name[], int sales[])
{
// get pointer to smallest element
auto iter = std::min_element(sales, sales + 5);
// get index of where the smallest element is
auto idx = std::distance(sales, iter);
// print out results
cout << "The lowest selling product is: " << name[idx] << endl;
cout << "The lowest price is: " << sales[idx] << endl;
}
For the largest element, use std::max_element instead of std::min_element.
After each of your for-loops, you are printing out the value in the array at index i. But i == 5 after the for-loop terminates, which is one-past the end of the array (note that i++ occurs one more time after the last iteration of the for-loop body is run). This is why you are getting garbage data (and why you might sometimes crash the program!)
In order to print out the lowest and highest values, you should just cout the variables that you've already taken the time to store:
cout << "The lowest selling product is: " << lowest << endl;
...
cout << "The highest selling product is: " << highest << endl;
Your print statement is at wrong place. You are printing value out of the loop where i is 5. You have written in 0 to 4 positions in the sales array. There is nothing at index 5. The below-corrected code should work -
void smallest(string name[], int sales[])
{
int i;
int lowest;
lowest = sales[0];
for (i = 1; i < 5; i++)
{
if (sales[i] < lowest)
{
lowest = sales[i];
}
}
cout << "The lowest selling product is: " << lowest << endl;
}
void biggest(string name[], int sales[])
{
int i;
int highest;
highest = sales[0];
for (i = 1; i < 5; i++)
{
if (sales[i] > highest)
{
highest = sales[i];
}
}
cout << "The highest selling product is: " << highest << endl;
}
The program should prompt the user to enter the number of jars sold for each type.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.
#include <iostream>
#include<string>
using namespace std;
int main()
{
const int SIZE=5;
string salsa_names[SIZE] = { "mild","medium","sweet","hot","zesty" },name1,name2;
double number_of_jars_sold[SIZE],total=0;
cout << "enter the number of jars sold for each of different types of salsa\n";
for (int i = 0; i < SIZE; i++)
{
cout <<"The salsa names are :"<<"'"<<salsa_names[i]<<"'";
cin >> number_of_jars_sold[i];
total += number_of_jars_sold[i];
}
double large=number_of_jars_sold[0],small=number_of_jars_sold[0];
cout << "The sales for each of salsa type is ="<<endl;
for (int i=0;i<SIZE;i++)
{
cout << salsa_names[i] << " : " << number_of_jars_sold[i] << endl;
}
cout << "total sale is equal to" << total << endl;
for (int i = 0; i < SIZE; i++)
{
if (large < number_of_jars_sold[i])
{
large = number_of_jars_sold[i];
name1=salsa_names[i];
}
}
for (int j = 0; j < SIZE; j++)
{
if (small > number_of_jars_sold[j])
{
small = number_of_jars_sold[j];
name2 = salsa_names[j];
}
}
cout << "The name of highest selling product is : " << name1 << endl;
cout << "The name of lowest selling product is : " << name2 << endl;
return 0;
}
Edited::
you should initialize small and large to zero first, add an if condition before this line if (small > number_of_jars_sold[j]):
if(small == 0), so you will have minimum value in small variable.
so the program needs to dynamically allocate an array large enough to hold a user=defined number of test scores. once all scores are entered, the array should be passed to a function that sorts them in ascending order. another function should be called that calculates the average score. the program should display the sorted list of scores and averages with appropriate headings. use pointer notation rather than array notation whenever possible.
the problem i am having is making it so that the program doesn't accept negative numbers for test scores.
here is the code.
source.cpp
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void arrSelectSort(float *, int);
void showArrPtr(float *, int);
void showAverage(float, int);
int main()
{
float *scores, //To dynamically allocate an array
total = 0.0, //Accumulator
average; //To hold the averge scores
int numScores; //To hold the number of test scores
//Get the number of test scores.
cout << "How many test scores would you like to process?";
cin >> numScores;
//Dynamically allocate an array large enough to hold that many
//test scores
scores = new float[numScores];
if (scores == NULL)
return 0;
//Get the test score for each test
cout << "Enter the test scores below.\n";
for (int count = 0; count < numScores; count++)
{
cout << "Test score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores <= 0)
{
cout << "Zero or negative numbers not accepted.\n";
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
}
}
//Calculate the total scores
for (int count = 0; count < numScores; count++)
{
total += scores[count];
}
//sort the elements of the array pointers
arrSelectSort(scores, numScores);
//Will display them in sorted order.
cout << "The test scores in ascending order are: \n";
showArrPtr(scores, numScores);
showAverage(total, numScores);
//Free memory.
delete[] scores;
return 0;
}
void arrSelectSort(float *array, int size)
{
int startScan, minIndex;
float minElem;
for (startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minElem = array[startScan];
for (int index = startScan + 1; index < size; index++)
{
if (array[index] < minElem)
{
minElem = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minElem;
}
}
void showArrPtr(float *array, int size)
{
for (int count = 0; count< size; count++)
cout << array[count] << " ";
cout << endl;
}
void showAverage(float total, int numScores)
{
float average;
//Calculate the average
average = total / numScores;
//Display the results.
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << average << endl;
system("pause");
}
modified source.cpp to use double instead of float
#include <iostream>
#include <iomanip>
using namespace std;
void arrSelectSort(double *, int);
void showArrPtr(double *, int);
double showAverage(double, int);
int main()
{
double *scores, //To dynamically allocate an array
total = 0.0, //Accumulator
average; //To hold the averge scores
int numScores; //To hold the number of test scores
//Get the number of test scores.
cout << "How many test scores would you like to process?";
cin >> numScores;
//Dynamically allocate an array large enough to hold that many
//test scores
scores = new double[numScores];
if (scores == NULL)
return 0;
//Get the test score for each test
cout << "Enter the test scores below.\n";
for (int count = 0; count < numScores; count++)
{
cout << "Test score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores[count] <= 0)
{
cout << "Zero or negative numbers not accepted.\n";
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
}
}
//Calculate the total scores
for (int count = 0; count < numScores; count++)
{
total += scores[count];
}
//sort the elements of the array pointers
arrSelectSort(scores, numScores);
cout << "The test scores in ascending order are: \n";
showArrPtr(scores, numScores);
showAverage(total, numScores);
delete[] scores;
return 0;
}
void arrSelectSort(double *array, int size)
{
int startScan, minIndex;
double minElem;
for (startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minElem = array[startScan];
for (int index = startScan + 1; index < size; index++)
{
if (array[index] < minElem)
{
minElem = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minElem;
}
}
void showArrPtr(double *array, int size)
{
for (int count = 0; count< size; count++)
cout << array[count] << " ";
cout << endl;
}
double showAverage(double total, int numScores)
{
double average;
//Calculate the average
average = total / numScores;
//Display the results.
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << average << endl;
system("pause");
}
errors -
Severity Code Description Project File Line Suppression State
Error C4716 'showAverage': must return a value ConsoleApplication9 c:\users\kenny\desktop\kenny_fepc1.cpp 85
Severity Code Description Project File Line Suppression State
Warning C4101 'average': unreferenced local variable ConsoleApplication9 c:\users\kenny\desktop\kenny_fepc1.cpp 12
please help fix. thank you.
You are not checking for the value that was input:
while (scores <= 0)
should be
while (scores[count] <= 0)
I guess this is homework and you are requested to use c-style arrays. However, please note that using a std::vector would make the task very much simpler as it has a dynamic size (that you dont have to handle "manually") and sorting a vector is trivial.
Btw I would suggest you to change the loop to
for (int count = 0; count < numScores; count++) {
scores[count] = -1;
while (scores[count] <= 0) {
cout << "Test Score #" << (count + 1) << "(has to be >0) : ";
cin >> scores[count];
}
}
Duplicate code is always a pain in the ass when you want to make changes to the code. Try to avoid it whenever possible (even if it is only two small lines).
Your other error appears because your showAverage is declared to return a double but it has no return. Either declare it to return nothing:
void showAverage(double total, int numScores)
or add a return statement at the end of the function:
return average;
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;
}