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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>

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.

May i ask for some help please.
Thanks in advance
Get rid of the inner for loop, you do want to keep the if/else if code
1
2
3
4
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:
1
2
3
4
5
6
7
8
9
10
#include <algorithm>

// ...

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.