Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

Linear Search using C programming

Use a recursive linearSearch function
to perform the linear search of the array. The function should receive an integer array and the size
of the array as arguments. If the search key is found, return the array subscript; otherwise, return –1.

Answer:


#include <stdio.h>
#define SIZE 100

// function prototypes
int linearSearch( int array[], int key, int low, int high );

int main( void )
{ 
   int array[ SIZE ]; // array to be searched
   unsigned int loop; // loop counter
   int searchKey; // element to search for
   int element; // result of linear search

   // initialize array elements
   for ( loop = 0; loop < SIZE; ++loop ) {
      array[ loop ] = 2 * loop;
   } // end for

   // obtain search key from user
   printf( "Enter the integer search key: " );
   scanf( "%d", &searchKey );

   // search array for search key
   element = linearSearch( array, searchKey, 0, SIZE - 1 );

   // display message if search key was found
   if ( element != -1 ) {
      printf( "Found value in element %d\n", element );
   } // end if
   else {
      printf( "Value not found\n" );
   } // end else
} // end main

// function to search array for specified key
int linearSearch( int array[], int key, int low, int high )
{ 
   // recursively search array
   if ( array[ low ] == key ) {
      return low;
   } // end if
   else if ( low == high ) {
      return -1;
   }
   else {
      return linearSearch( array, key, low + 1, high );
   }
}


About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!