15,662,426 members
See more:
//here is the code, there is no output.
//here I am trying to count the number of iterations in a binary search program.
C#
```#include<stdio.h>
int main()
{ int array[10]={2,10,44,55,66,78,87,89,90},m,left,right,key=90,counter;
left=0;
right=8;
while(left<=right)
{ m=(left+right)/2;
if(key==array[m])
{counter++; return 1;}
else if(key>array[m])
{counter++; left=m+1;}
else
{counter++; right=m-1;}
}
printf("the number of iterations are %d",counter);
return 0;

}```
Posted
Graham Breach 19-Feb-14 13:02pm
There is a `return 1;` in your loop - if you hit that, the `printf` will not be reached.

## Solution 2

Because your implementation is not correct. Try:
C#
```#include<stdio.h>
int main()
{
int array[]={2,10,44,55,66,78,87,89,90},m,left,right,key=90,counter=0;
left=0;
right=sizeof(array)/sizeof(array[0]) -1;

while(left <= right)
{
m=(left+right)/2;
counter++;
if(key == array[m])
break;
else if(key>array[m])
left = m + 1;
else
right=m-1;
}
printf("the number of iterations are %d\n",counter);
if ( key == array[m])
printf("the item was found at index %d\n", m);

return 0;

}```

Sergey Alexandrovich Kryukov 19-Feb-14 13:27pm
5ed.
—SA

## Solution 1

you are kidding ;-)
the program is ending by "return 1;
you can use the break statement.

tips:

1. every statement on ONE line. even a declarations of int
2. every bracket on ONE line.
3. use the debugger in single step mode

Reason: the code stays cleaner and readble when it gets more.

Sergey Alexandrovich Kryukov 19-Feb-14 13:34pm
This is the correct answer, but... All three of your {1, 2, 3} items look utterly naive. For 1-2, if you simply said that the code should be neat, but why should anyone follow your particular formatting rule you have copied from somebody (or some samples) taught you?

If you read this, probably you can understand that you are a victim of imprinting (or a beneficiary of imprinting — it depends on the point of view :-).

A person make less mistakes if the code is well readable, that's all.

As to #3... single steps is a sure way to waste more time for debugging than it is required. Ever heard of breakpoints? watches? call stack? Sorry, I don't mean to hurt you; I'm nearly sure you know it all, but why do you advise the slowest method (which of course should be used in some cases)?

—SA
KarstenK 20-Feb-14 2:16am
I wrote this because:

so I wanted him to learn the basics complete.
Sergey Alexandrovich Kryukov 20-Feb-14 2:24am
It would be very, very good of you, only if you gave him really useful advice, if you really explained a lot of extra things on more basic level. But your advice is misleading, I explained why.

If you simply only explained him that some code is unreachable because of return statement and advised to use break, it would be a good answer. But the tips spoiled the picture.

—SA