Sensor extremes
A weather station writes its temperature readings for one day on a single line, separated by spaces. The station manager wants the day's summary: the highest reading, the lowest reading, and the range (highest minus lowest).
Read the line, split it into numbers, and print the three values.
Input
One line with between 1 and 200 integers separated by single spaces. Each reading is between -100 and 100.
Output
Three lines: Max: h, Min: l and Range: r where r = h - l.
Example 1
Input
12 -3 7 22 5
Output
Max: 22 Min: -3 Range: 25
The highest reading is 22 and the lowest is -3; 22 - (-3) = 25.
Example 2
Input
4
Output
Max: 4 Min: 4 Range: 0
With a single reading the maximum and minimum are the same value.
Constraints
- 1 <= number of readings <= 200
- -100 <= each reading <= 100
Hints
Hint 1 of 3
Start max and min at the first reading, not at 0: every reading might be negative, or every reading might be positive.
Hint 2 of 3
Walk the array once with foreach, updating max when you see something larger and min when you see something smaller.
Hint 3 of 3
The array also has LINQ helpers: readings.Max() and readings.Min() do the scan for you.
Solution
Show a reference solution and explanation
string line = Console.ReadLine()!;
int[] readings = line.Split(' ').Select(int.Parse).ToArray();
int max = readings[0];
int min = readings[0];
foreach (int r in readings)
{
if (r > max) max = r;
if (r < min) min = r;
}
Console.WriteLine($"Max: {max}");
Console.WriteLine($"Min: {min}");
Console.WriteLine($"Range: {max - min}");
Why it works
The classic mistake here is initialising max to 0: on the input -20 -5 -40 no reading is greater than 0, so max would stay 0 and be wrong. Seeding both trackers with readings[0] avoids that, and the guarantee of at least one reading makes readings[0] safe. One foreach pass then compares each value against both trackers. Split(' ') turns the line into strings and Select(int.Parse) converts each one, so the arithmetic works on real integers rather than text.