Week 3 Discussion Forum

Linear Search's full code with line by line explanation

Linear Search's full code with line by line explanation

by Md. Mazbaur Rashid (MMR) -
Number of replies: 0

#include<stdio.h>


void Search(int arr[], int n, int element)     //Receiving values with necessary parameters.

{

    int bull = 0;                 //Initialization of variable bull to check condition.

    for(int i = 0; i < n; i++)                   //Loop to check all the array's element.

    {

        if(element == arr[i])                 //Condition to check whether the element is available or not.

        {

            printf("Element found at position number %d of the array\n", i+1);                 //if found it will print a message with the position.

            bull++;                              //Also increase the value of bull by 1. If the value is more than 0, the if condition below will be true.

        }

    }

    if(!bull)                       //Initialize the bull to 0, that means it is false when the value of bull stay 0, in condition false means "!".

    {

         printf("Element not found");

    }

}


int main()

{

    int n;                      //Declaring necessary variable

    printf("Enter array size: ");

    scanf("%d",&n);                         //Taking the array size from the user.

    int arr[n], element;                      //Declaring necessary variables

    printf("Enter elements: ");

    for(int i = 0; i < n; i++)               //Loop for taking all the elements from user.

    {

        scanf("%d", &arr[i]);            //taking array's elements from the user.

    }

    printf("Enter what you want to search: ");

    scanf("%d",&element);                //Taking search element from the user.

    Search(arr, n, element);                //Passing necessary arguments.

    return 0;                     //Stopping the program

}


211 words