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;

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.

About Author

Related Posts

C# Reference Types

Understanding C# Reference Types

One of the key features of C# is its support for C# reference types, which allow developers to create complex, object-oriented applications. In this blog post, we…

c# value types

Understanding C# Value Types

C# is a powerful programming language that is widely used for developing a wide range of applications. One of the key features of C# is its support…

C# check if server is online

C# check if server is online directly from your code. Check servers or services like web servers, database servers like MySQL and MongoDB. You can probably check…

C# Convert Int to Char

C# convert int to char google search is giving some result which I think is not directly what some people want. Most results are giving instructions on…

c# bash script

C# Bash Script Made Easy

There are many reasons why it could be handy to run a bash script from a C# application. In 2014, before I changed to a Mac as…

go hello world

Golang Hello World, Get a Easy Fantastic Start

Golang hello world example tutorial. I assume you are new to the golang language since you found this website. Go is one of the latest programming languages…

Leave a Reply