How to find position (array index ) of a number in a given array? I have to find the position (array index) of a number in an array, the number can lie in between any other two numbers in the array. I have written code for this but I want some alternative way to do this.

example: let the array be given as

float arr[]={1.5, 3.65, 4.9, 8.4, 10.6, 17.5, 19.45, 21.86, 25.67, 30.65}; 


Now I have to find the position of 12.6 in the given array, since 12.6 lies between 10.6 and 17.5 in the above array so, it should return array index as 4.  

Is there any other way to do this? I know it can be done by using binary search but I don't know how to implement it (since the number is not present in array)

The array is sorted (ascending order) 

#include&lt;stdio.h&gt;
int main()
{
int position;
int i;
float num=12.6; // position of this number has to be determined i.e. it lies between 10.6
// and 17.5 in the array given below so it should give array index as 4
float arr[]={1.5, 3.65, 4.9, 8.4, 10.6, 17.5, 19.45, 21.86, 25.67, 30.65}; // any random array

for(i=0;i&lt;10;i++)
{
if(arr[i] &gt; num)
{
position=i-1;
break;
}
}
printf("array index is %d",position); // this gives index as 4

return 0;
}
Indent the Code

Most computer code is indented, in some languages indentation is used to show the level of complexity of the code, in other languages the code won't work properly unless it is indented.

Declare the Variables as They are Needed

The integer variable i can be declared in the for loop and that will limit the scope to just the for loop.

for(int i = 0; i &lt; 10; i++)
{
    if(arr[i] &gt; num)
    {
        position = i - 1;
        break;
    }
}


Horizontal Spacing

To make the code more readable, put spaces between the operators and the operands as shown above in the for loop example. Squashing all the code together makes it very difficult to understand what the code is actually doing.

Performance

First run the -O3 optimizer during compilation and linking. If the program were more complicated than it is then use a profiling tool such as gprof.

Linear searches are known to be a slower way to do things.

I think the position reported is off by one, if I was using this code to do an insertion sort, I wouldn't subtract one from position. 

Shorten the Code.

There are 2 shorter ways to subtract 1 from position.

    --position;


and

    position -= 1;