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;
}
Related
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.
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
So I have succeeded in confusing the hell out of myself in doing this. I am trying to get it to calculate the average of the weights entered into the array minus the lowest weight in the array. I'm using functions and somewhere along the line I confused myself with passing variables. It would be much appreciated if someone could give me a pointer and tell me if I'm way off base or not. Also how would I compare the values entered to a validation code? I have a line commented out that I was fiddling with, but never got working.
#include <iostream>
using namespace std;
int getWeight();
int findLowest(int arrayWeight);
double calcAverage(int weight);
bool askToContinue();
int main(){
do{
int weights = getWeight();
double lowest = findLowest(weights);
double average = calcAverage(weights);
}
while(askToContinue());
}
int getWeight() {
//Variables
int weights[5]; //array
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
cin >> weights[counter];
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
return -1;
/*
do
{
//Gather user input of amount of discs
cout << "How many discs do you wish to purchase?" << endl;
cout << "Please enter a number between 1 and 1,000,000" << endl;
cin >> weights;
cout << endl;
validAmount = (weights > 5) && (weights <= 500); // Tests if the amount entered is valid
if (!validAmount) // Prompts user amount entered was invalid
{
cout << "Invalid Amount. Please try again!" << endl;
}
}
while(!validAmount); // Runs loop again if the amount entered was not valid
return discs;
*/
}
int findLowest(int arrayWeight){
int lowWeight = 999999;
if(lowWeight > arrayWeight)
{
lowWeight = arrayWeight;
}
cout << arrayWeight;
system("PAUSE");
return arrayWeight;
}
double calcAverage(int weight){
//Variables
float avgWeight = 0;
int sumWeight = 0;
//Calls findLowest function to find lowest value
int lowestWeight = findLowest(weight);
//Calculates the average score
return weight;
}
bool askToContinue() // Asks the user if they want to continue. If yes, the loop restarts. If no, the program exits.
{
char userResponse = ' ';
bool validInput = false;
do
{
cout << endl;
cout << "Do you wish to continue?" << endl;
cout << "Enter y for 'yes' or n for 'no'" << endl;
cin >> userResponse;
validInput = (userResponse == 'y') || (userResponse == 'n');
if (!validInput)
{
cout << "Invalid response. Please try again!" << endl;
}
} while (!validInput);
return(userResponse == 'y');
}
You have a number of issues, the first being you need to understand the data types you're working with. You should declare the array once and then pass around a pointer to that array. These are a better set of declarations and for convenience set up a constant for the number of weights.
#include <iostream>
using namespace std;
const int numWeights = 5;
void getWeights(int weights[]);
int findLowest(int weights[]);
double calcAverage(int weights[]);
bool askToContinue();
int main() {
do {
int weights[numWeights];
getWeights(weights);
double average = calcAverage(weights);
cout << "Average: " << average << endl;
}
while (askToContinue());
}
getWeights was mostly ok, but use the passed in array.
void getWeights(int weights[]) {
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
int weight;
cin >> weight;
while (weight < 5 || weight > 500)
{
cout << "Invalid weight, should be between 5 and 500" << endl;
cin >> weight;
}
weights[counter] = weight;
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
}
For findLowest you need to keep track of the lowest value and the lowest index. By remembering the index of the lowest value, you will make the average easier. Your 99999 magic number isn't needed since we know there will always be a lowest value in your set. Start with index 0 and the first value. If you find something smaller, update the value and index. When the loop ends you'll have the first index of the lowest value. Note that the loops starts at 1 (the second item).
int findLowest(int weights[]) {
int lowestVal = weights[0];
int lowestIndex = 0;
for (int i=1; i<numWeights; i++) {
if (weights[i] < lowestVal) {
lowestVal = weights[i];
lowestIndex = i;
}
}
return lowestIndex;
}
For the average find the lowest index, add up all the weights but skip the index of the lowest, convert to double so you can get a good average and return the value.
double calcAverage(int weights[]) {
int lowestIndex = findLowest(weights);
int total = 0;
for (int i=0; i<numWeights; i++) {
if (i != lowestIndex) {
total += weights[i];
}
}
return (double)total/(double)(numWeights-1);
}
This function is not accurately returning the highest and lowest values entered into the array. I'm not sure what I code I entered for the program to do this. This program needs to return the average of all of the elements entered into the array (the average part works fine) as well as find the highest and lowest values among all of the values entered into the array. Please help!
#include <iostream>
using namespace std;
float temptotal = 0;
float averagetemp = 0;
float temperatures[50];
float average(int);
void highest(int);
void lowest(int);
int main()
{
int days = 0;
cout << "Enter the number of days: ";
cin >> days;
if (days > 50)
{
cout << "You may only enter temperatures for 50 days." << endl;
return 0;
}
average(days);
highest(days);
lowest(days);
}
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
}
averagetemp = temptotal / days;
cout << "The average temperature is: " << averagetemp << endl;
return averagetemp;
}
void highest(int days)
{
int count;
int highest;
highest = temperatures[50];
for (count = 1; count < days; count++)
{
if (temperatures[count] > highest)
highest = temperatures[count];
cout << "The highest temperature is: " << highest << endl;
}
}
void lowest(int days)
{
int count;
int lowest;
lowest = temperatures[50];
for (count = 1; count < days; count++)
{
if (temperatures[count] < lowest)
lowest = temperatures[count];
cout << "The lowest temperature is: " << lowest << endl;
}
}
This function
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
//...
is already wrong because element temperatures[0] will not be uninitialized. You have to write
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i-1];
temptotal += temperatures[i-1];
//...
Or
float average(int days)
{
for (int i = 0; i < days; i++)
{
cout << "Enter the temperature for day number " << i + 1 << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
//...
Functions highest and lowest are also wrong. For example array temperatures has no element with index 50. Moreover the user can enter number of days less than 50. So this statement
highest = temperatures[50];
is wrong.
The functions can be written like this function definition
void highest( int days )
{
int highest = temperatures[0];
for ( int count = 1; count < days; count++ )
{
if ( highest < temperatures[count] ) highest = temperatures[count];
}
cout << "The highest temperature is: " << highest << endl;
}
Take into acccount that there are standard algorithms std::max_element, std::min_element, std::minmax_element declared in header <algorithm> that can be used instead of your functions.
For example function highest can be defined with using standard algorithm std::max_element the following way
#include <algorithm>
//...
void highest( int days )
{
cout << "The highest temperature is: "
<< *std::max_element( temperatures, temperatures + days )
<< endl;
}
Array indices start with a 0
Place the cout statements outside the for loop.
Arrays are indexed from 0 to n-1, where n is the total number of entries in the array. You started the count at 1 in your loop when you should start at 0. If the user entered 50 values, you would have had an out-of-bounds access.
The correction should be:
for (int i = 0; i < days; i++)
Then in your output statement, it should be:
cout << "Enter the temperature for day number " << i+1 << ": ";
The other issue is your highest function. The issue are a few things:
You declared the local variable highest as an int. It should be a float to match the type used in the temperature array.
You should set highest to a very small value, smaller than any you would expect. Or better yet, set it to the first temperature entry before the loop, and start the loop from the second entry.
You named your local variable highest, but your function name is also highest. This will lead to confusion when someone else looks at your code.
If you're interested in another solution, the following computes the highest:
#include <algorithm>
//...
void highest(int days)
{
float theHighest = *std::max_element(temperatures, temperatures + days);
cout << "The highest temperature is: " << theHighest << endl;
}
A little better version from the function 'highest':
void highest(int days)
{
if (days < 1)
{
cout << "No temperatures" << endl;
}
double highest = temperatures[0];
for (int count = 1; count < days; count++)
{
if (temperatures[count] > highest)
{
highest = temperatures[count];
}
}
cout << "The highest temperature is: " << temperatures[highest_index] << endl;
}
All arrays in C++ starting with index 0. In this implementation this point is considered by using the first element (index 0) as thie first highest value. After that the loop has only to deal with the rest, begining at index 1.
The variable 'highest' must be from the type double. Otherwise you may get wrong results, because the highest is a little lower than the real highest due to generaly rounding down (double to int). The next comparison may be assigned even if it is a little lower.
Array indices start with 0 but your loops start at 1. For your loop over days, for instance, this will iterate over the full range:
for (int i = 0; i < days; i++)
The problem is:
A Class of 40 students has received their grades for 5 exams. Implement a function that calculates the worst average grade and display the the IDs of all students having the worst average grade.
I already calculated the average but do not know how to calculate the WORST average ( as in the lowest average of the 40 students) and displaying the ID numbers that have this number.
This is what I have written so far:
#include<iostream>
#include <iomanip>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
int main()
{
float avg;
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
cout << "Enter an ID number: " << endl;
cin >> x[i];
cout << "Enter 5 grades: " << endl;
for (int j = 0; j < 5; j++)
{
cin >> y[j];
while (y[j]>100)
{
cout << "Please enter a valid grade that is less than a 100: " << endl;
cin >> y[j];
}
total += y[j];
}
avg = total / 5;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg << endl;
}
Something like this:
Note: I have added some important statements!
#include<iostream>
#include <iomanip>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
float AVG[MAX_NUM];
int worstIDCount = 0;
int main()
{
float avg, min = 1001;
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
avg = 0;
total = 0;
cout << "Enter an ID number: " << endl;
cin >> x[i];
cout << "Enter 5 grades: " << endl;
for (int j = 0; j < 5; j++)
{
cin >> y[j];
while (y[j]>100)
{
cout << "Please enter a valid grade that is less than a 100: " << endl;
cin >> y[j];
}
total += y[j];
}
avg = total / 5;
AVG[i] = avg;
if(avg < min)
min = avg;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg << endl;
}
for(int i = 0; i < MAX_NUM; i++)
{
if(AVG[i] == min)
cout << "Student with WORST Average: ID" << x[i] << endl;
}
};
So you want to store these averages in a std::vector<float>, std::sort it and get the lowest. Then go back and find the students that have that average.
working example
#include <iostream>
#include <vector>
#include <functional> // mem_fn
#include <algorithm> // sort, upper_bound
#include <iterator> // ostream_iterator
struct Student_average {
int student_id;
float average;
};
bool compare_student_averages(Student_average const &lhs,
Student_average const &rhs) {
return lhs.average < rhs.average;
}
int main() {
std::vector<Student_average> averages;
// collect the data and populate the averages vector
// ...
sort(begin(averages), end(averages), compare_student_averages);
std::cout << "The worst average is: " << averages.front().average << '\n';
auto end_of_worst_student_averages =
upper_bound(begin(averages), end(averages), averages.front(),
compare_student_averages);
std::cout << "The IDs of the students with the worst averages are:\n";
transform(begin(averages), end_of_worst_student_averages,
std::ostream_iterator<int>(std::cout, "\n"),
std::mem_fn(&Student_average::student_id));
}
Here is a more C++ way of doing this using std::accumulate and std::min_element (I removed the check for anything > 100, for brevity):
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
int main()
{
float avg[5];
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
cin >> x[i]; // ID
for (int j = 0; j < 5; ++j)
cin >> y[j]; // grades
// compute the average for this student
avg[i] = std::accumulate(y, y + 5, 0) / 5.0F;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg[i] << endl;
}
// compute the worst average
float* worst_average = std::min_element(avg, avg + MAX_NUM);
// get the position in the array where the worst is found
int position = std::distance(avg, worst_average);
// output results
cout << "This person has the worst average: " << x[position]
<<". The average is " << *worst_average << "\n";
}
Note that the averages are stored in an array. The way the average is computed for each person is to use std::accumulate to add up the y array values, and then divide by 5.0.
Since we now have the averages in an aray, we want to find the smallest item in the array. To do that, min_element is used to get us the position of where the element is stored.
The trick here is that min_element returns a pointer to the smallest item, so we need calculate how far this pointer is located from the beginning of the avg array. To do this, the std::distance function is used. This now gives us the position of the smallest item.
The rest of the code just outputs the results.
As you can see, the only loops involved were the input loops. The calculation of the average and the worst average were done using accumulate and min_element, respectively.