Here is what I have. I have notes in the code where I'm having trouble towards the bottom. I'm trying to find the total average of the grades entered by the user. The user has put in four different grades near the bottom. They are weighted as 10% of the grade.
The Programs are 30% and the exercises are 10%. The final Exam is 30%. Please just give me advice on what to do. Don't tell me the code. I want to try and figure the code out on my own before asking for additional help so that I learn this. I just want advice on what steps to take next. Thanks.
#include <iostream>
#include <string>
#include <vector>
#include <numeric>
using namespace std;
float average(const vector<float> &values);
int main()
{
cout << "Kaitlin Stevers" << endl;
cout << "Program 11" << endl;
cout << "December 8th 2016" << endl;
cout << endl;
cout << endl;
vector<float> exerciseGradesVector;
float exerciseGrades;
cout << "Enter the grades for the Exercises. Type 1000 when you are finished." << endl;
while ( std::cin >> exerciseGrades && exerciseGrades != 1000 )
{
exerciseGradesVector.push_back (exerciseGrades);
}
cout << endl;
cout << "You entered " << exerciseGradesVector.size() << " grades." << endl;
cout << endl;
cout << "The Exercise grades you entered are : ";
for(int i=0; i < exerciseGradesVector.size(); i++)
{
cout << exerciseGradesVector[i] << " ";
}
cout << endl;
float averageExerciseGrades = average( exerciseGradesVector );
cout << "The average of the Exercise grades is: " << averageExerciseGrades << endl;
cout << endl;
vector<float> programGradesVector;
float programGrades;
cout << "Enter the grades for the Programss. Type 1000 when you are finished." << endl;
while ( std::cin >> programGrades && programGrades != 1000 )
{
programGradesVector.push_back (programGrades);
}
cout << endl;
cout << "You entered " << programGradesVector.size() << " grades." << endl;
cout << endl;
cout << "The Program grades you entered are : ";
for(int i=0; i < programGradesVector.size(); i++)
{
cout << programGradesVector[i] << " ";
}
cout << endl;
float averageProgramGrades = average( programGradesVector );
cout << "The average of the Program grades is: " << averageProgramGrades << endl;
cout << endl;
float midTermTest;
float midTermProgram;
float finalExamTest;
float finalExamProgram;
cout << "Please enter the Midterm Exam score for the multipule choice section. " << endl;
cin >> midTermTest;
cout << "Please enter the Midterm Exam score for the Programming section. " << endl;
cin >> midTermProgram;
cout << "Please enter the Final Exam score for the multipul choice section. " << endl;
cin >> finalExamTest;
cout << "Please enter the Final Exam score for the Programming section. " << endl;
cin >> finalExamProgram;
///////I need to find the average off ALL the grades.. All the 4 inputs above and the two vectors need to be in the average.
///////I am not sure if I need to read the 3 numbers before the last one into a vector because each is worth 10 percent and then do the next step or what. Would that mess it up? Advice please?
vector<float> allGradesVector;
float totalaverageGrade = average( allGradesVector ); //This is obviously not finished. Just ignore it..
}
float average( const vector<float> &values )
{
float sum = 0.0;
for ( size_t i = 0; i < values.size(); i++ ) sum += values[i];
return values.size() == 0 ? sum : sum / values.size();
}
I would suggest to rewrite the loops like this
do
{
cin >> exerciseGrades;
exerciseGradesVector.push_back (exerciseGrades);
}
while (exerciseGrades != 1000);
the following way
while ( std::cin >> exerciseGrades && exerciseGrades != 1000 )
{
exerciseGradesVector.push_back (exerciseGrades);
}
In this case there is no need to use a strange variable like dropOne.
To find the average is easy. The function can look the following way
float average( const std::vector<float> &values )
{
float sum = 0.0f;
for ( float x : values ) sum += x;
return values.size() == 0 ? sum : sum / values.size();
}
Or if the compiler does not support the range-based for loop you can write
float average( const std::vector<float> &values )
{
float sum = 0.0f;
for ( size_t i = 0; i < values.size(); i++ ) sum += values[i];
return values.size() == 0 ? sum : sum / values.size();
}
To call the function you can write for example in main
float averageExerciseGrades = average( exerciseGradesVector );
The function must be declared before its usage that is for example before main
float average( const std::vector<float> &values );
though it may be defined after main.
A simple for loop will do the trick.
float total = 0;
int count = 0
for(int i = 0; i < dropOnee; i++)
{
total+= programGradesVector[i];
count++;
}
cout << "The average is: " total/count << endl;
I'd also recommend using more descriptive name's for the counts.
You can use std::accumulate
float average = accumulate(programGradesVector.begin(), programGradesVector.end(), 0.0) / programGradesVector.size();
I would suggest to use while to replace do while. Because you may input 1000 firstly.
You can write like this:
while ( std::cin >> exerciseGrades && fabs(exerciseGrades - 1000) < 0.000001 )
{
exerciseGradesVector.push_back (exerciseGrades);
}
I use fabs function to solve float is inaccuracy in sometime.
About averages function:
You can use std::accumulate:
float average = accumulate(programGradesVector.begin(), programGradesVector.end(), 0.0) / programGradesVector.size();
or implement it by yourself like this:
float average( const std::vector<float> &values )
{
float sum = 0.0f;
int nSize = values.size();
for(int i = 0; i < nSize; ++i)
{
sum += values[i];
}
return nSize == 0 ? sum : sum / nSize;
}
Related
#include <iostream>
using namespace std;
int main()
{
int n, G;
float num[500], sum=0.0, average,Grades;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 500 || n <= 0)
{
cout << "Error! number should in range of (1 to 500)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(G = 0; G < n; ++G)
{
cout << G + 1 << ". Enter number: ";
cin >> num[G];
sum += num[G];
}
average = sum / n;
Grades = num[G] >= average;
cout<<endl;
cout << "Grades Average = " << average << endl;
cout << "Grades above or equal the Average : " <<Grades<< endl;
cout << "Number of grades above the Average = "<<(int) Grades;
return 0;
}
i coded this code but the Number of grades above the Average and Grades above or equal the Average don't work it just print 0
i tried to print the Grades >= the avg but it print 0
also num of Grades also print 0
where is the error ?
I think you was trying to do something like this:
...
int grades_on_avg, upper_grades = 0;
for(int i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
for(int i = 0; i < n; ++i) // use separate for loop and redefined index
{
if(num[i] == average) // compare to average
grades_on_avg++;
else if(num[i] > average) // if bigger than average
upper_grades++;
}
cout<<endl;
cout << "Grades Average = " << average << endl;
cout << "Grades above or equal the Average =" << (grades_on_avg + upper_grades) << endl;
cout << "Number of grades above the Average = "<< upper_grades ;
You assign boolean value to Grades variable. Also, you refer to element outside of the array: G variable is equal to n after exiting for-loop, but max index you can use is n - 1 (basic programming rule). So, you should change your code into something like this:
...
int avgGrades{0};
int avgAboveGrades{0};
for(int i{0}; i < n; ++i)
{
if(num [i] == average)
{
++avgGrades;
}
else if(num [i] > average)
{
++avgAboveGrades;
}
}
If you prefer more elegant ways of doing so, you can use std::count_if() function but it's more tricky and requires knowledge about lambdas.
I created a program to display an average from an array of numbers the user have decided to input. The program asks the user the amount of numbers he / she will input, then they input all positive numbers. The output for the average is always a decimal, how can I only display the whole number without any decimal points. Ex. 12.34 = 12 / 8.98 = 8
#include <iostream>
#include <iomanip>
using namespace std;
void sortingTheScores(double *, int);
void showsTheScoresNumber(double *, int);
double averageForAllScores(double, int);
int main()
{
double *scores;
double total = 0.0;
double average;
int numberOfTestScores;
cout << "How many test scores do you have? ";
cin >> numberOfTestScores;
scores = new double[numberOfTestScores];
if (scores == NULL)
return 0;
for (int count = 0; count < numberOfTestScores; )
{
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores[count] <= 0)
{
cout << "Value must be one or greater: " ;
cin >> scores[count];
}
count = count +1;
}
for (int count = 0; count < numberOfTestScores; count++)
{
total += scores[count];
}
sortingTheScores(scores, numberOfTestScores);
cout << "The numbers in set are: \n";
showsTheScoresNumber(scores, numberOfTestScores);
averageForAllScores(total, numberOfTestScores);
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << averageForAllScores(total,numberOfTestScores);
return 0;
}
void sortingTheScores (double *array, int size)
{
int sorting;
int theIndex;
double theNumbers;
for (sorting = 0; sorting < (size - 1); sorting++)
{
theIndex = sorting;
theNumbers = array[sorting];
for (int index = sorting + 1; index < size; index++)
{
if (array[index] < theNumbers)
{
theNumbers = array[index];
theIndex = index;
}
}
array[theIndex] = array[sorting];
array[sorting] = theNumbers;
}
}
void showsTheScoresNumber (double *array, int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
double averageForAllScores(double total, int numberOfTestScores)
{ double average;
average = total / numberOfTestScores;
return average;
}
You can use I/O manipulators here:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setprecision(0) << 1.231321 << '\n';
}
Output:
1
You can do it without using iomanip library:
std::cout.precision(0);
std::cout << 1.231321 << std::endl;
Then you'll simply get:
1
Just you need to use std::cout.precision() which is equivalent to std::setprecision() from iomanip library.
Edit:
The aforementioned solution is okay for smaller floating point values, but if you try something like 1334.231321, the std::cout will result displaying some scientific notation, something like:
1e+03
which is actually odd to read and understand. To solve it, you need std::fixed flag, you may write something like:
std::cout.precision(0), std::cout << std::fixed;
std::cout << 1334.231321 << std::endl;
Then it'll show:
1334
For numbers in a +/-2^31 range you can do:
cout << int(12.34) << " " << int(8.98) << endl;
which produces output
12 8
You may also want to consider rounding to the nearest integers. To do so
add a line
#include <cmath>
then do
cout << int(rint(12.34)) << " " << int(rint(8.98)) << endl;
this gives
12 9
This is a question i am working on:
Prompt the user to enter five numbers, being five people's weights. Store the numbers in a vector of doubles. Output the vector's numbers on one line, each number followed by one space.
Also output the total weight, by summing the vector's elements.
Also output the average of the vector's elements.
Also output the max vector element.
So far this is the code i have
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
int maxWeight = 0;
int temp = 0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": ";
cout << inputWeights[i]<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++) {
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
When i run this code, whatever inputs i use(for the cin>>(...)), i get all zero's as output and i do not know why. can i get some help please.
update
cleaned up the code a little by getting rid of the cout<< inputWeights[i]<< endl;
and by adjusting vector inputWeights; at the beginning of the program.But the outputs are still not exactly what they are supposed to be. Instead, only the first 2 inputted values make it as outputs. Any reason why? thanks
update this is the right or correct code. Hope it helps someone in future.
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector <float> inputWeights;
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
float maxWeight = 0.0;
float temp = 0.0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": "<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++){
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
You're making a vector of size 5:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
// == 0, 0, 0, 0, 0
Then, in your input loop, you're adding new values to the end:
inputWeights.push_back (42);
// == 0, 0, 0, 0, 0, 42
Then you're outputting the first five elements which were always zero.
You need to choose one thing or the other: either set the size of the vector at the start of the program, or grow the vector with push_back for as long as there's input. Both are valid options.
You can clean up your code and fix the problems by adopting modern C++ (as in, C++11 and later) idiom. You don't need to fill your code with for(int i = 0; i < something; i++) any more. There's a simpler way.
// Size fixed in advance:
vector<float> weights(NUM_WEIGHTS);
for (auto& weight : weights) { // note it's `auto&`
cout << "\nEnter next weight: ";
cin >> weight; // if it was plain `auto` you'd overwrite a copy of an element of `weight`
}
// Size decided by input:
vector<float> weights; // starts empty this time
cout << "Enter weights. Enter negative value to stop." << endl;
float in;
while (cin >> in) {
if(in < 0) {
break;
}
weights.push_back(in);
}
In either case, you can then play with the filled vector using another range-based for:
cout << "You entered: ";
for (const auto& weight : weights) {
cout << weight << " ";
}
You'll also need to remove the cout << inputWeights[i] << endl; line from your input loop if you resize the vector during input - as written you'd be reading elements which don't exist yet, and will probably get an array-index-out-of-bounds exception.
When you create define your inputWeights you are putting 5 items into it with default values.
vector<float> inputWeights(NEW_WEIGHT);
Change it to be just
vector<float> inputWeights;
And get rid of this line in your code or comment it out
cout << inputWeights[i]<< endl;
This is what you are looking for from the requirements of your program.
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
unsigned i = 0;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " ";
}
std::cout << std::endl;
double totalWeight = 0.0;
std::cout << "The total of all weights is: ";
for ( i = 0; i < weights.size(); ++i ) {
totalWeight += weights[i];
}
std::cout << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: ";
double max = weights[0];
for ( i = 0; i < weights.size(); ++i ) {
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << max << std::endl;
return 0;
}
The culprit to your problem for seeing all 0s as output is coming from these two lines of code:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
which is the same as doing this:
vector<float> inputWeights{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
you are then looping through up to 5 elements using NEW_WEIGHT when it would be easier to use inputWeights.size() when traversing through containers.
Edit - Condensed Version
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
unsigned i = 0;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
double totalWeight = 0.0;
double max = weights[0];
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " "; // Print Each Weight
totalWeight += weights[i]; // Sum The Weights
// Look For Max Weight
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << std::endl;
std::cout << "The total of all weights is: " << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: " << max << std::endl;
return 0;
}
I have to write a program that allows to calculate the arithmetic average of an arbitrary numbers of values (chosen by the user)
It will outputs:
Number: 34
Number: 36
Number: 44
Number: //and I choose to stop input pressing
//Outputs:
It was inserted 3 numbers and the avarage is: 38
Of course i've forgot to post what i've done:
for (int x = 0; x < 50; x++){
cout << "Number: ";
cin >> number[x];
cout << "You have inserted the " << x << " element of the array;" << endl;
sum += number[x];
avarage = sum / number[x];
nEelementi = number[x];}
so I run the program, input some numbers, press something like ctrl+d or trying to add something to the code.. but it only goes from the first to the last element of the array with no values, becouse not entered, of course.. and then print absurd avarage and sum.
I know I don't need an array to do this but it's required from the exercise.. also the exercise only request to use for or while loop and arrays.
What I need is a way to stop the input and calculate the sum and avarage of only what I wrote.
edit1.
I've tried to dived by n writing for(x = 0; x < n, x++) because it made sense to me, but i think it "thinks" n, wrote like this, infinite, because the results is 0 (because the limit of a number divided by infinite is 0).. so i've started becoming mad.
Now i've started thinking that it would be easier to use while loop! and wrote
#include <iostream>
using namespace std;
int main() {
int num[50];
double sum = 0;
double average = 0;
int cont;
int end = 0;
while (cont < 50) {
cout << "num: ";
cin >> num[cont];
sum += num[cont];
cont++;
cout << "Want to continue 0 = sì, 1 = no";
cin >> end;
if (end == 1) {break;}
}
average = sum / cont;
cout << "You have insert " << cont << " elements" << endl;
cout << "LThe sum is: " << sum << endl;
cout << "The avarage is: " << average << endl;
return 0;
}
BUT still doesn't work. My professor says you should be able to stop input number by pressing ctrl+d so I'm not doing good.
Sorry for late answer but i have also to translate the code.. hope all translation is good:)
edit2.
#include <iostream>
int main() {
int sum = 0;
int num;
while ( std::cin ) {
std::cout << "Number: ";
std::cin >> num;
}
if ( std::cin >> num ) {
sum += num;
num++;
}
else {
std::cin.clear();
std::cout << "Input interrupted" << std::endl;
}
std::cout << "Sum is " << sum << std::endl;
std::cout << "You have entered " << num << " numbers" << std::endl;
return 0;
}
I love this new code, very simple and understandable to me, but I was not able to add sum operation, it only outputs 0! (leaving out average)
And also I was not able to determinate, and display, how many numbers I've entered. The last row of the code is just an example of what I want to do..
edit3.
Finally I made it.
#include <iostream>
using namespace std;
int main(){
double numero;
int index = 0;
double somma = 0.;
cout << "Inserire un numero: ";
while( cin )
{
if ( cin >> numero )
{
somma = somma + numero;
index++;
cout << "Inserire un numero: ";
}
else
{
cout << "Input interrotto" << endl;
}
}
cout << "Sono stati inseriti " << index << " numeri e la lora media è:
<< somma / index << endl;
return 0;
}
Thanks so much!
P.S. To the end, I don't need to use an array, it's just simple
There are a few problems here. One is that if the stream errors due to being closed or bad input, you don't recover and you just charge through your loop.
So first, make the loop terminate early if necessary. I'm also going to convert it to a while loop in preparation for the next part.
int x = 0;
while( std::cin && x < 50 )
{
std::cin >> number[x++];
}
Now it terminates early if the stream errors. But what if the user typed in "hello"? You could ignore it and continue like this:
if( std::cin >> number[x] )
{
x++;
}
else
{
std::cin.clear();
}
Notice that I didn't compute the sum or anything inside the loop. There's no need, since you are already putting them in an array. You can just do it after the loop. Here, I'm using std::accumulate
double sum = std::accumulate( number, number + x, 0.0 );
double average = 0.0;
if( x > 0 ) average = sum / x;
Now, you have also said you want an arbitrary number of values. Your original code allowed up to 50. Instead of storing them, you can instead just compute on the fly and discard the values.
double sum = 0.0;
int count = 0;
while( std::cin )
{
double value;
if( std::cin >> value )
{
sum += value;
count++;
}
else
{
std::cin.clear();
}
}
double average = 0.0;
if( count > 0 ) average = sum / count;
If you still want to store the values along the way, you can use a vector.
std::vector<double> numbers;
//...
numbers.push_back( value );
And if you want the user to choose the number of values:
std::cout << "Enter number of values: " << std::flush;
std::size_t max_count = 0;
std::cin >> max_count;
std::vector<double> numbers;
numbers.reserve( max_count );
while( std::cin && numbers.size() < max_count )
{
// ...
}
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.