I'm trying to return the largest and the smallest numbers in an array as an array
for example:
int[] arr = {5, 1, 2, 4, 9, 10, 200}
public static int[] largest_smallest(int[] arr)
{
int max = array_values.Max();
int min = array_values.Min();
//return array with largest and smallest numbers
}
How do I modify my code so it can have an output of: [200, 1]
?
CodePudding user response:
like this
int [] result = { min, max};
return result;
CodePudding user response:
Here is a code example that returns an array with the smallest and the largest number:
int[] arr = { 3, 1, 2, 4, 9, 10, 200 };
int[] largestAndSmallest(int[] arr)
{
int[] result = new int[2];
result[0] = arr[0];
result[1] = arr[0];
for (int i = 1; i < arr.Length; i )
{
if (arr[i] > result[1])
{
result[1] = arr[i];
}
if (arr[i] < result[0])
{
result[0] = arr[i];
}
}
return result;
}
Console.WriteLine(string.Join(", ", largestAndSmallest(arr)));
CodePudding user response:
Using System.Linq;
int[] op_array = {};
op_array[0] = array_values.Max();
op_array[1] = array_values.Min();