Exercise
Function Getminmax
Objective
Write a C# function named "GetMinMax", which will ask the user for a minimum value (a number) and a maximum value (another number). It should be called in a similar way to
GetMinMax( n1, n2);
which would behave like this:
Enter the minimum value: 5
Enter the maximum value: 3.5
Incorrect. Should be 5 or more.
Enter the maximum value: 7
That is: it should ask for the minimum value and then for the maximum. If the maximum is less than the minimum, it must be reentered. It must return both values.
Write Your C# Exercise
C# Exercise Example
// Import the System namespace to use basic classes like Console
using System;
class Program
{
// Function to ask for minimum and maximum values and validate that max >= min
public static void GetMinMax(out double minValue, out double maxValue)
{
// Prompt the user to enter the minimum value
Console.Write("Enter the minimum value: ");
minValue = Convert.ToDouble(Console.ReadLine());
// Ask for the maximum value, ensuring it's greater than or equal to the minimum value
while (true)
{
Console.Write("Enter the maximum value: ");
maxValue = Convert.ToDouble(Console.ReadLine());
// If the maximum is less than the minimum, prompt the user to re-enter the maximum
if (maxValue >= minValue)
{
break; // Exit the loop if the maximum is valid
}
else
{
Console.WriteLine($"Incorrect. Should be {minValue} or more.");
}
}
}
// Main function to test the GetMinMax function
public static void Main()
{
double minValue, maxValue;
// Call the GetMinMax function and capture the user input
GetMinMax(out minValue, out maxValue);
// Display the results
Console.WriteLine($"The minimum value is: {minValue}");
Console.WriteLine($"The maximum value is: {maxValue}");
}
}