Programming Examples

Cpp program to search an element in an array using binary search


Write a program to search an element in a sorted array 

Solution

#include<iostream>
using namespace std;
int main(){
    int arr[50],size,i,item,upper,lower=0,mid,flag=0;
    cout<<"Enter the desired array size "<<endl;
    cin>>size;
    cout<<"Enter the elements(Sorted in ascending order) "<<endl;
    for(i=0;i<size;i++)
    {
        cin>>arr[i];
    }
    cout<<"Enter the element to be searched for :";
    cin>>item;
    upper=size-1;
    while(lower<=upper)
    {
        mid=(upper+lower)/2;
        if(item==arr[mid])
        {
            flag=1;
            break;
        }
        else if(item<arr[mid])
        {
            upper=mid-1;
        }
        else
        {
            lower=mid+1;
        }
    }
    if(flag==1)
    {
        cout<<"Element found at index "<<mid<<" position "<<mid+1;
    }
    else
    {
        cout<<"Element not found"<<endl;
    }
    return 0;
}
Output

Enter the desired array size 

10

Enter the elements(Sorted in ascending order) 

2

3

5

9

12

15

20

23

25

30

Enter the element to be searched for :20

Element found at index 6 position 7

Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz