Let's say you have a list of items {4, 2, 5, 3}.
The average is the easiest part, you have to use a for loop to sum each variable, and then divide by 4.0 (the number of items in your list) to get the average. have a variable called "sum" that you use to accumulate the total before you divide by class_size.
sum = 0
sum += 4
sum += 2
sum += 5
sum += 3
sum / 4.0 == the average
With min and max, declare two variables where you store what the min and max of the array are "so far".
For example, with the above array, you iterate through it with a for loop, and you need to check if the current element is less greater than the element you have stored as the max (so far). If the current element is greater than what you have as the maximum, that element becomes the new maximum.
int max = -1000; // start off as an impossibly low number
check 4 --> is 4 greater than -1000? Yes, 4 is now the max number.
check 2 --> is 2 greater than 4? No, 4 is still the max.
check 5 --> is 5 greater than 4? Yes, 5 is now the max number.
check 1 --> is 1 greater than 5? No, 5 is still the max number
et viola, 5 is your max.
Do almost the same thing with min.
Note that arrays start at index 0, not 1.
Also: Variable-length arrays are not allowed in C++, an array size must be a compile-time constant to be used in that manner (class_size). You either have to create a dynamic array or an std::vector.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int class_size;
cout << "How many students are in your class? ";
cin >> class_size;
cout << endl;
std::vector<int> exam_score(class_size);
for(int i = 0; i < class_size; i++)
{
cout << "What is the final score for student " << i+1 << ": ";
cin >> exam_score[i];
}
}
|