Linear Search in Array in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Linear Search in Array in C: Program to Search an Element

📑 On this page:
  • Introduction
  • C Program for Linear Search
  • Sample Output
  • Program Explanation
  • Algorithm
  • Practice Exercise
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • What is linear search and how it works
  • How to implement linear search in C
  • How to handle both found and not found cases
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to perform linear search in an array.

Linear search is the simplest searching algorithm. It works by checking each element of the array one by one from the beginning until the target element is found or the end of the array is reached.

Linear search is used in many real-world applications, such as:

  • Finding a contact in an unsorted phonebook
  • Searching for a product in a list
  • Finding a student record by roll number
  • Checking if a value exists in a dataset

💡 Key Point: Linear search works on both sorted and unsorted arrays. It is simple to implement but can be slow for large arrays.

C Program for Linear Search in Array

#include <stdio.h>

int main() {
    int n, i, search;
    int found = 0;  // Flag to track if element is found
    
    // Ask user for number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    // Declare array
    int arr[n];
    
    // Read elements into the array
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Get element to search
    printf("\nEnter the element to search: ");
    scanf("%d", &search);
    
    // Linear search
    for(i = 0; i < n; i++) {
        if(arr[i] == search) {
            printf("\nElement %d found at position %d (index %d)\n", 
                   search, i + 1, i);
            found = 1;
            break;  // Exit loop after finding first occurrence
        }
    }
    
    // If element not found
    if(found == 0) {
        printf("\nElement %d not found in the array.\n", search);
    }
    
    return 0;
}

Sample Output

Enter the number of elements: 6
Enter 6 elements:
10 20 30 40 50 60

Enter the element to search: 40

Element 40 found at position 4 (index 3)

When Element is Not Found:

Enter the number of elements: 5
Enter 5 elements:
10 20 30 40 50

Enter the element to search: 100

Element 100 not found in the array.

Example with Duplicate Elements:

Enter the number of elements: 7
Enter 7 elements:
10 20 10 30 10 40 50

Enter the element to search: 10

Element 10 found at position 1 (index 0)

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int n; — number of elements
    • int i; — loop counter
    • int search; — element to search for
    • int found = 0; — flag (0 = not found, 1 = found)
  3. Get User Input: Reads the array elements from the user.
  4. Get Search Element: Asks the user for the element to search.
  5. Linear Search:
    • The for loop iterates through each element
    • If arr[i] == search, the element is found
    • Prints the position and index
    • Sets found = 1 and breaks out of the loop
  6. Handle Not Found: If found == 0, prints "Element not found".
  7. Return: return 0; indicates successful program execution.

📝 Note: Linear search finds the first occurrence of the element. If there are duplicates, it returns the first match.

Linear Search Algorithm

Step-by-step algorithm:

  1. Start
  2. Read the array elements
  3. Read the element to search (target)
  4. Set found = 0
  5. For i = 0 to n-1:
    • If arr[i] == target:
      • Print "Element found at position i+1"
      • Set found = 1
      • Break the loop
  6. If found == 0:
    • Print "Element not found"
  7. End

Visual Example

Searching for 40 in the array [10, 20, 30, 40, 50]:

Step 1: Check arr[0] = 10 → Not equal to 40

Step 2: Check arr[1] = 20 → Not equal to 40

Step 3: Check arr[2] = 30 → Not equal to 40

Step 4: Check arr[3] = 40 → Match found!

Result: Element found at position 4 (index 3)

Linear Search Using Function

Here's a version using a separate function for better code organization:

#include <stdio.h>

int linearSearch(int arr[], int n, int search) {
    for(int i = 0; i < n; i++) {
        if(arr[i] == search) {
            return i;  // Return index if found
        }
    }
    return -1;  // Return -1 if not found
}

int main() {
    int n, search, result;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d elements:\n", n);
    for(int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    printf("\nEnter the element to search: ");
    scanf("%d", &search);
    
    result = linearSearch(arr, n, search);
    
    if(result != -1) {
        printf("\nElement %d found at position %d (index %d)\n", 
               search, result + 1, result);
    } else {
        printf("\nElement %d not found in the array.\n", search);
    }
    
    return 0;
}

Time and Space Complexity

Scenario Time Complexity
Best Case (Element at first position) O(1)
Worst Case (Element at last position or not found) O(n)
Average Case O(n)
Space Complexity O(1)

💻 Practice Exercise

Challenge 1: Modify the program to find all occurrences of the search element and print their positions.

Challenge 2: Count the number of occurrences of the search element in the array.

🔍 Click to Show Solution for Challenge 2
#include <stdio.h>

int main() {
    int n, i, search;
    int count = 0;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    printf("\nEnter the element to search: ");
    scanf("%d", &search);
    
    // Count occurrences
    for(i = 0; i < n; i++) {
        if(arr[i] == search) {
            count++;
        }
    }
    
    if(count > 0) {
        printf("\nElement %d found %d time(s) in the array.\n", search, count);
    } else {
        printf("\nElement %d not found in the array.\n", search);
    }
    
    return 0;
}

Frequently Asked Questions

1. What is linear search in C?

Linear search is a simple searching algorithm that checks each element of an array one by one from the beginning until the target element is found or the end of the array is reached.

2. What is the time complexity of linear search?

The time complexity is O(n) in the worst case and O(1) in the best case (when the element is at the first position).

3. When should I use linear search?

Use linear search when the array is small or unsorted. For large sorted arrays, use binary search for better efficiency.

4. Can linear search be used on a sorted array?

Yes, linear search works on both sorted and unsorted arrays. However, binary search is more efficient for sorted arrays.

5. What is the difference between linear and binary search?

Linear search checks elements one by one and works on any array. Binary search is faster but requires a sorted array. Binary search has O(log n) time complexity compared to O(n) for linear search.

💡 Tip: Linear search is the simplest searching algorithm. It's a great starting point for learning about searching algorithms.

📖 Related Tutorials

  • Sort Array in Descending Order
  • Search in Sorted Array
  • Find Second Largest Element
  • More Array Assignments

Previous Topic: -->> Sort Array in Descending Order   ||   Next topic: -->> Search in Sorted Array


📚 Explore More Topics

🗄️ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

🐍 Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

☕ Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.