In: Computer Science
Find MIN. Write a C# console app consisting of class MIN with the method CalculateMin() and the driver class. Print the MIN and MIN's location. Don't count numbers outside the range [0, 100].
// C# program to create a class MIN with method CalculateMin that returns the index of the minimum element in the input array
using System;
class MIN {
// method that determines and return the index of the
minimum element in the input array, arr, if found else returns
-1
// It only considers the numbers in the range [0,
100]
public static int CalculateMin(double[] arr)
{
int minIdx = -1; // set minIdx to -1 i.e no minimum element
// loop over the array
for(int i=0;i<arr.Length;i++)
{
// validate ith
number is in valid range
if(arr[i] >= 0 && arr[i] <= 100)
// check that if minIdx is not set or ith element < minIdx
element, update minIdx to i
if(minIdx == -1 || arr[i] <
arr[minIdx])
minIdx = i;
}
// return the index of the minimum element
return minIdx;
}
}
class MINDriver
{
static void Main() {
// create an array of numbers
double[] arr = {67, 50, 70.5, 12, -3, 102, 45, 16, 12, 66,
23};
// get the index of the minimum
element in the above arr
int idx =
MIN.CalculateMin(arr);
// minimum element exists, display
the minimum element and its index
if(idx != -1)
Console.WriteLine("Minimum element is "+arr[idx]+" at index:
"+idx);
else // no minimum element exists in the valid range
Console.WriteLine("Array does not contain any valid
elements");
}
}
//end of program
Output: