Home > Back-end >  C program goes into a never-ending input cycle
C program goes into a never-ending input cycle

Time:05-29

This is a simple binary search program, but for some reason, the program just doesn't move on after asking for the value of the key from the user. At first, I thought it is an issue with my compiler, but it still happens wherever I paste the code, and I don't know why.

#include <iostream>
using namespace std;

int binary(int arr[], int n, int k){
    int s = 0; 
    int e = n; 
    int mid = (s e)/2; 
    while(s<=e){
        if(k==arr[mid]){
            return mid; 
        }
        else if(k>arr[mid]){
            s = mid 1; 
        }
        else if(k<arr[mid]){
            e = mid-1; 
        }
    }
    return -1;
}

int main(){
    int i, n, key;
    cin>>n; 
    int a[n];

    for(i=0;i<n;i  ){
        cin>>a[i];
    }
    cout<<"Enter key:"<<endl;
    cin>>key;

    cout<< binary(a, n, key); 
}

Instead of moving on after k, the code just does nothing.

image

CodePudding user response:

you code is looping in the 'binary ' function

try this to see

while(s<=e){
    cout << s << e; <<<===== 

learn to use your debugger to step through the code

CodePudding user response:

The middle element is found inside the loop in binary search because the search interval is reduced to half in every iteration. Your mid is not changing that is why the program is not terminating.

So final code after correction is:

#include <iostream>
using namespace std;
int binary(int arr[], int n, int k)
{
int s = 0;
int e = n;
while (s <= e)
{
    int mid = (s   e) / 2;
    if (k == arr[mid])
    {
        return mid;
    }
    else if (k > arr[mid])
    {
        s = mid   1;
    }
    else if (k < arr[mid])
    {
        e = mid - 1;
    }
}
return -1;
}

int main()
{
int i, n, key;
cin >> n;
int a[n];

for (i = 0; i < n; i  )
{
    cin >> a[i];
}
cout << "Enter key:" << endl;
cin >> key;

cout << binary(a, n, key);

}

I hope it helps! Please upvote if you like:).

  • Related