DS Practical Slip 3 Q A

C Program for Linear (Sequential) Search in an Array

Linear Search is the simplest searching technique in C programming. It checks each element one by one until the required element is found.


📝 Problem Statement

Q1. A) Write a C program to accept n elements from user, store it in an array. Accept a value from the user and use Linear/Sequential search method to check whether the value is present in array or not. Display proper message.


💡 Logic (Simple Student-Friendly Steps)

  1. Declare an array.
  2. Read the number of elements (n).
  3. Read n elements into the array.
  4. Accept the value to search.
  5. Use a for loop:
    • Compare each element with the search value.
    • If found, display “Element found”.
  6. If not found after checking all elements, display “Element not found”.

👉 Linear search checks elements one by one from beginning to end.


💻 Source Code (Simple Version)

#include <stdio.h>

int main()
{
    int arr[100], n, i, key;
    int found = 0;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter elements:\n");
    for(i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }

    printf("Enter value to search: ");
    scanf("%d", &key);

    for(i = 0; i < n; i++)
    {
        if(arr[i] == key)
        {
            found = 1;
            break;
        }
    }

    if(found == 1)
        printf("Element found in the array.");
    else
        printf("Element not found in the array.");

    return 0;
}

🖥️ Sample Output

Enter number of elements: 5
Enter elements:
10
20
30
40
50
Enter value to search: 30
Element found in the array.

Another Sample Output

Enter number of elements: 4
Enter elements:
5
15
25
35
Enter value to search: 10
Element not found in the array.

🎓 Viva Questions with Answers

1. What is Linear Search?

Linear search is a method of searching where elements are checked one by one.

2. What is the time complexity of Linear Search?

O(n), because in the worst case all elements are checked.

3. Is sorting required for Linear Search?

No, sorting is not required.

4. What is the advantage of Linear Search?

It is simple and works on both sorted and unsorted arrays.

5. What is the disadvantage of Linear Search?

It is slower for large arrays compared to binary search.

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top