### Arrays into arrays - finding max and min?

so the program is 5 users input: Name >> age >> colour >> score
using struct.

e.g.
Andy 1 red 69
Bob 2 blue 44
Cat 5 red 57
Dennis 12 yellow 87
Elsa 32 red 45

i want to find people for example under the colour "red" and find the minimum and maximum score under that colour.

minimum = Else 45
maximum = Andy 69

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859`` ``````#include #include using namespace std; struct info { string name; int age; string colour; int score; }; int main() { info student[5]; // An array contains 5 students information string name; int age; string colour; int score; int count = 5; int i =0; for (i=0; i < 5; i++) { cin >> student[i].name >> student[i].age >> student[i].colour >> student[i].score; } cout << endl << "Students in red team:" << endl; int minred, maxred; for (i = 0; i < 10; ++i) if (student[i].colour == "red") { minred = student[i].score; maxred = student[i].score; for(i=1; i<5; i++) { if(minred > student[i].score) { minred=student[i].score; } else if (maxred < student[i].score) { maxred=student[i].score; } } } cout<<"Maximum mark in RED is: "<< maxred << endl; cout<<"Minimum mark in RED is: "<< minred << endl; system("pause"); return 0; }``````

The code works... but it calculates min and max for the whole 5 arrays and not specifically the red team.

Get rid of the inner for loop, you do want to keep the if/else if code
 ``1234`` ``````for(i=1; i<5; i++) { // KEEP CODE INSIDE THIS LOOP }``````
but the first for loop runs throught he whole data
the second is the ones containing red...
and i dont think its suppose to be 5 .. no idea why i put that there :/

i tried what you said, but i got the last number 45 for both the minimum and maximum?
You could simplify your code a little if you used things from the C++ library.
One of the things would be using std::list instead of arrays, but that's not too important in your case.
Two immediately useful things would be std::min() and std::max() from the algorithm library.

Your for() loops are dubious, and they should use count instead of a hardcoded value, like 5 or 10.

And so, your second for() loop could be rewritten as:
 ``12345678910`` ``````#include // ... for (i=0; i < count; ++i) if (student[i].colour == "red") { minred = std::min(minred, student[i].score); maxred = std::max(maxred, student[i].score); }``````

http://cplusplus.com/reference/algorithm/min/
http://cplusplus.com/reference/algorithm/max/
Topic archived. No new replies allowed.