简体   繁体   中英

returning the largest and smallest numbers as an array

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] ?

like this

 int [] result  = { min, max};

 return result;

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)));

Using System.Linq;

int[] op_array = {};

op_array[0] = array_values.Max();

op_array[1] = array_values.Min();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM