Perform Linear Search on integer Arrays in C

Linear Search on integer Arrays in C

This C program demonstrates basic functionalities for handling integer arrays. It allows users to input integers into an array, prints the array, and performs linear searches based on user input until the user enters 0 to terminate.

This program uses a predefined array size and provides flexibility for user input. This is a fully functional program however you can further improve it with input validation, dynamic memory allocation, and improved error handling.

#include <stdio.h>

#define NMAX 10

int getIntArray(int a[], int nmax, int sentinel);
void printIntArray(int a[], int n);
int linear(int a[], int n, int who);


int main(void) {
    int x[NMAX];
    int hmny;
    int who;
    int where;

    hmny = getIntArray(x, NMAX, 0);
    printf("The array was: \n");
    printIntArray(x, hmny);
    printf("Now we do linear searches on this data\n");
    do {
        printf("Enter integer to search for [0 to terminate] : ");
        scanf("%d", &who);
        if (who == 0)break;
        where = linear(x, hmny, who);
        if (where < 0) {
            printf("Sorry, %d is not in the array\n", who);
        }
        else
            printf("%d is at position %d\n", who, where);
    } while (1);
}

//  n is the number of elements in the array a.
//  These values are printed out, five per line.
void printIntArray(int a[], int n)
{
    int i;


    for (i = 0; i < n; ) {
        printf("\t%d ", a[i++]);
        if (i % 5 == 0)
            printf("\n");
    }
    printf("\n");
}

// It reads up to nmax integers and stores then in a; sentinel
// terminates input. 
int getIntArray(int a[], int nmax, int sentinel)
{
    int n = 0;
    int temp;


    do {
        printf("Enter integer [%d to terminate] : ", sentinel);
        scanf("%d", &temp);
        if (temp == sentinel) break;
        if (n == nmax)
            printf("array is full\n");
        else
            a[n++] = temp;
    } while (1);
    return n;
}

// Given the array a with n elements, searches for who.
// It returns its position if found, otherwise it returns -1. 
int linear(int a[], int n, int who)
{
    int lcv;
    for (lcv = 0;lcv < n;lcv++)
        if (who == a[lcv])return lcv;
    return (-1);
}
procedure LINEAR_SEARCH (array, value)
   for each item in the array
      if match element == value
         return index
      end if
   end for
end procedure
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post