Skip to main content

Simple Linear Search Example Program Using Functions in C++

2 min read Updated June 30, 2026
Share:
On this page (6sections)

About this program

This is an example program in searching programs. Read the concept first: Understanding Array in C++, then study the code and output below.

Definition

  • Linear search is also called sequential search
  • Linear search is a method for searching a value within a array.
  • It sequentially checks one by one of the array for the target element until a match is found or until all the elements have been searched of that array.
/* Simple Linear Search Program Using Functions in C++*/
/* Data Structure C++ Programs,C++ Array Examples */

#include <iostream>
#include<conio.h>
#include<stdlib.h>

#define MAX_SIZE 5

using namespace std;

void linear_search(int[], int);

int main() {
    int arr_search[MAX_SIZE], i, element;

    cout << "Simple C++ Linear Search Example - Array and Functions\n";
    cout << "\nEnter " << MAX_SIZE << " Elements for Searching : " << endl;
    for (i = 0; i < MAX_SIZE; i++)
        cin >> arr_search[i];

    cout << "\nYour Data   :";
    for (i = 0; i < MAX_SIZE; i++) {
        cout << "\t" << arr_search[i];
    }

    cout << "\nEnter Element to Search : ";
    cin>>element;

    //Linear Search Function
    linear_search(arr_search, element);

    getch();
}

void linear_search(int fn_arr[], int element) {
    int i;

    /* for : Check elements one by one - Linear */
    for (i = 0; i < MAX_SIZE; i++) {
        /* If for Check element found or not */
        if (fn_arr[i] == element) {
            cout << "\nLinear Search : Element  : " << element << " : Found :  Position : " << i + 1 << ".\n";
            break;
        }
    }

    if (i == MAX_SIZE)
        cout << "\nSearch Element : " << element << "  : Not Found \n";
}

Sample Output

Output 1:

Simple Linear Search Example - Array and Functions

Enter 5 Elements for Searching :
900
333
21
16
24
Enter Element to Search : 16
Linear Search : 16 is Found at array : 4.

Output 2:

Simple Linear Search Example - Array and Functions

Enter 5 Elements for Searching :
90
32
323
11
22
Enter Element to Search : 33

Search Element : 33  : Not Found

Learn the concept first, then study the code:

Frequently Asked Questions

What does this C++ program do?
It is a C++ example program that demonstrates Simple Linear Search Using Functions, including the complete source code and the expected sample output.
How do I compile and run this C++ program?
Save the code in a `.cpp` file, compile it with `g++ filename.cpp -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses loops to iterate over data, arrays and conditional logic, illustrating a common pattern in C++ programming.

Related Tutorials

Search tutorials