May 27, 2020

soltveit.org

..Geekish..

C# Array find the first number above target

C# Array find the first number above target. If the array is sorted and you need to find the first number above your target number. Here is a way to solve that.

int numbers[] = new int {1, 4, 7, 8, 9};
int target = 5;
int result;

foreach (float number in numbers) 
{
  if (target < number) 
  {
    result = number;
    break;
  }
}

Console.WriteLine("Result: " + result.ToString());
// Output
// Result: 7

You could also make it into a function if you need to. It would be something like this. This time with floats instead of integers.

float FindNumber(float[] array, float target)
{
    foreach (float number in array)
    {
        if (target < number)
        {
            return number;
        }
    }

    return 0; // Return 0 or anything else if no number was found
}

How to use the function.

float numbers[] = new int {1.21, 4.65, 7.55, 8.90, 9.12};
float target = 5.0;

Console.WriteLine(FindNumber(numbers, target));

// Output
// 7.55

Check out the other Unity articles here.

Or the Unity Learning Premium.