Introduction to Computer Science - Fall 2004

/* Author:Yana
Module: linSearch.c

What:
-----
Searching a number in an unsorted list array
and returning its location if found.
Input: N integers separated by a space from
each other, followed by the number
to search.
Output: The location of the number, if found
or an appropriate message otherwise.
Assumption on input: valid.

How
-----
Algorithm: Linear search
*/

#include < stdio.h >
#defne SIZE 10 /* size of input */

/* function prototypes */
int LinearSearch (int A[], int size, int val) ;

int main (){

    int array[SIZE]; /* array for input */
    int i; /* index in the array */
    int number; /* A number to search */
    int location; /* Location of number in list, if exists, -1 if doesn't exist */

    /* read input */
    printf("Please enter %d integers \n" , SIZE);
    for (i = 0; i < SIZE; i++){
      scanf("%d", &array[i] );
    }

    printf("\nPlease enter a number to locate: ");
    scanf("%d", &number);

    /* locate number */
    location = LinearSearch(array, SIZE, number);
    if (location != -1 )
      printf("The value %d appears in place %d \n", number, location );
    else
      printf("The value %d is not in the given array\n ", number);

    return 0;
}

/* LinearSearch: Search a given number in an array of numbers.
Parameters: A - array to search (input parameter)
size - size of the array (input parameter)
val - value to search (input parameter)
Returns: the index of the searched element in the array or -1 if the element is not in the array
Algorithm: linear search. */

int LinearSearch (int A[], int size, int val){

    int i = 0 ; /* current index searched */
    int found = 0; /* 0 - not found; 1 - found */
    int place = -1;

    while ( ( i < size ) && ( !found ) ){
      if (A[i] == val){
        place = i ;
        found = 1 ;
      }
      else
        i++ ;
    }
    return (place);
}