How to Find the Position of an Element in Array

Binary Search or Half Interval Search informs about the Index Number of a Value within a Given Array.We Solve this Problem with Function so beginners can Understand the basic Logic of the program. 

Source Code 


#include <iostream>
using namespace std;

int searchFunction( const int [], int, int ); // prototype

 int main()
 {
   const int size = 100;     // size of array a
   int a[ size ];       // create array a
   int searchNumber;        // value to locate in array a
   cout<<endl<<endl<<"********** LINEAR SEARCH ARRAY FUNCTION ************"<<endl<<endl<<endl;
   cout<<endl<<endl<<"********** SEARCH BETWEEN 2 TO 200 ************"<<endl<<endl<<endl;
   for ( int i = 0; i < size; i++ )
   a[ i ] = 2 * i;        // create some data
  
   cout << "Enter integer search key: ";
   cin >>searchNumber;
  
              // attempt to locatesearchNumber in array a
   int element = searchFunction( a,searchNumber, size );
  
              // display results
   if ( element != -1 )
   cout << endl << "Found value in element " << element << endl<<endl;
   else
   cout << "Value not found" << endl<<endl;
  
   return 0;         
}            // end main
  
              
int searchFunction( const int array[], int key, int sizeOfArray )

{
 for ( int j = 0; j < sizeOfArray; j++ )
             // compare key to every element of array until location is
  if ( array[ j ] == key )      // if found,
   
    return j;         // return location of key

 return-1;            // key not found
 } 

Output of the Program

Enter Number and Search it

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment