Write code to do Linear Search in an Array?

Data Structure >   Searching >   Linear Search  

Long Question

434


Answer:

 /* Program for linear search an element */
#include <stdio.h>
#include <conio.h>

void main()
{
    int array[10];
    int i, N, keynum, found = 0;
    clrscr();
    printf("Enter the value of N\n");
    scanf("%d", &N);
    printf("Enter the elements one by one\n");
    for(i = 0; i < N; i++)
        scanf("%d", &array[i]);
    printf("Input array is\n");
    for(i = 0; i < N; i++)
        printf("%d\n", array[i]);
    printf("Enter the element to be searched\n");
    scanf("%d", &keynum);
    /* Linear search begins */
    i = 0;
    while(i < N && found == 0)
    {
        if(keynum == array[i])
            found = 1;
        i++;
    }
    if(found == 1)
        printf("SUCCESSFUL SEARCH\n");
    else
        printf("Search is FAILED\n");
} /* End of main */


The code is an implementation of the linear search algorithm in C language. The purpose of the code is to search for a specific element in an array of integers entered by the user.

The code starts with the inclusion of necessary header files i.e. stdio.h and conio.h, which contain standard input/output and console input/output functions respectively.

The main() function is defined, which contains integer type array named 'array', integer variables 'i', 'N', 'keynum' and 'found'. 'N' represents the number of elements in the array entered by the user, 'keynum' represents the element to be searched and 'found' is a flag variable to indicate if the element is found in the array or not.

The clrscr() function is used to clear the screen before taking input from the user. The user is prompted to enter the value of 'N' and then prompted to enter 'N' integers one by one, which are stored in the array.

The input array is then displayed to the user. The user is then prompted to enter the element to be searched ('keynum').

The linear search algorithm is then implemented using a while loop. The loop iterates from the first element of the array until either the element is found or the end of the array is reached. If the 'keynum' is found in the array, the 'found' variable is set to 1.

Finally, the result of the search is displayed to the user. If the element is found, the message "SUCCESSFUL SEARCH" is displayed, otherwise, the message "Search is FAILED" is displayed. The program ends with the end of the main function.


This Particular section is dedicated to Question & Answer only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.