For working professionals
For fresh graduates
More
Explore C Tutorials: From Begi…
1. Introduction to C Tutorial
2. Addition of Two Numbers in C
3. Anagram Program in C
4. Armstrong Number in C
5. Array in C
6. Array of Pointers in C
7. Array of Structure in C
8. C Program to Find ASCII Value of a Character
9. Assignment Operator in C
10. Binary Search in C
11. Binary to Decimal in C
12. Bitwise Operators in C
13. Boolean in C
14. C Compiler for Mac
15. C Compiler for Windows
16. C Function Call Stack
17. C Language Download
18. Operators in C
19. C/C++ Preprocessors
20. C Program for Bubble Sort
21. C Program for Factorial
22. C Program for Prime Numbers
23. C Program for String Palindrome
24. C Program to Reverse a Number
25. Reverse a String in C
26. C string declaration
27. String Input Output Functions in C
28. Calculator Program in C
29. Call by Value and Call by Reference in C
30. Ceil Function in C
31. Coding Vs. Programming
32. Command Line Arguments in C/C++
33. Comments in C
34. Compilation process in C
35. Conditional Statements in C
36. Conditional operator in the C
37. Constant Pointer in C
38. Constants in C
39. Dangling Pointer in C
40. Data Structures in C
41. Data Types in C
42. Debugging C Program
43. Convert Decimal to Binary in C
44. Define And include in C
45. Difference Between Arguments And Parameters
46. Difference Between Compiler and Interpreter
47. Difference Between If Else and Switch
48. Do While Loop In C
49. Double In C
50. Dynamic Array in C
51. Dynamic Memory Allocation in C
52. Enumeration (or enum) in C
53. Evaluation of Arithmetic Expression
54. Factorial of A Number in C
55. Features of C Language
56. Fibonacci Series Program in C Using Recursion
57. File Handling in C
58. For Loop in C
59. Format Specifiers in C
60. Functions in C
61. Function Pointer in C
62. goto statement in C
63. C Hello World Program
64. Header Files in C
65. Heap Sort in C Program
66. Hello World Program in C
67. History of C Language
68. How to compile a C program in Linux
69. How to Find a Leap Year Using C Programming
70. Identifiers in C
71. If Else Statement in C
72. If Statement in C
73. Implementation of Queue Using Linked List
74. Increment and decrement operators in c
75. Input and Output Functions in C
76. How To Install C Language In Mac
77. Jump Statements in C
78. Lcm of Two Numbers in C
79. Length of an Array in C
80. Library Function in C
81. Linked list in C
82. Logical Operators in C
83. Macros in C
84. Matrix multiplication in C
85. Nested if else statement in C
86. Nested Loop in C
87. One Dimensional Array in C
88. Operator Precedence and Associativity in C
89. Overflow And Underflow in C
90. Palindrome Program in C
91. Pattern Programs in C
92. Pointer to Pointer in C
93. Pointers in C: A Comprehensive Tutorial
94. Pre-increment And Post-increment
95. Prime Number Program in C
96. Program for Linear Search in C
Now Reading
97. Pseudo-Code In C
98. Random Access Files in C
99. Random Number Generator in C
100. Recursion in C
101. Relational Operators in C
102. Simple interest program in C
103. Square Root in C
104. Stack in C
105. Stack Using Linked List in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
112. String Comparison in C
113. String Functions in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
118. Structure of C Program
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
122. Toupper Function in C
123. Transpose of a Matrix in C
124. Two Dimensional Array in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
129. User Defined Functions in C
130. What is Variables in C
131. Is C language case sensitive
132. Fibonacci Series in C
Linear search is a simple method to check each element one by one. It starts from the first until it finds a match or reaches the end of the array. If a match is found, it returns the element's index. If no match is found by the end, the element is considered absent.
In this tutorial, you’ll learn how to write a program for linear search in C, with simple examples for easy understanding.
Improve your C programming skills with our Software Development courses — take the next step in your learning journey!
Linear search algorithm sequentially compares each element in a list to the target. It’s a basic approach useful for small datasets, such as searching for a contact in a phonebook, verifying user credentials in a system, or finding a specific item in a warehouse inventory.
The idea behind it is straightforward:
Let’s use an example to understand these steps:
Input:
Process:
Output: Key found at Index 2
Explanation: The algorithm starts from index 0 and checks each element in the list. When it reaches index 2, the value 30 matches the target value (key), and it stops. It then returns the index (2) where the element was found.
Also Read: Difference Between Linear Search and Binary Search
With the basic understanding of linear search in place, let’s now look at how to implement it in C using a simple function.
A linear search algorithm in C is used to find an element in an array. C is often used for this algorithm due to its low-level control over memory and efficient handling of arrays.
Unlike higher-level languages, C allows direct memory access and optimized performance for tasks like linear search, making it ideal for simple search operations in small to medium-sized datasets.
Here's a program for linear search in C using a function:
#include <stdio.h>
// Function to perform linear search
int linearSearch(int arr[], int n, int target) {
// Traverse through the array
for (int i = 0; i < n; i++) {
// If the target element is found, return its index
if (arr[i] == target) {
return i;
}
}
// If the target element is not found, return -1
return -1;
}
int main() {
int arr[] = {5, 9, 3, 7, 2}; // Array to search in
int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array
int target = 7; // Element to search for
// Call the linearSearch function
int result = linearSearch(arr, size, target);
// Check if the element was found and print the result
if (result == -1) {
printf("Element not found\n");
} else {
printf("Element found at index %d\n", result);
}
return 0;
}
Explanation:
1. The linearSearch function takes three arguments:
2. The function loops through each element of the array:
3. In the main function:
4. Then, you call the linearSearch function to search for the target in the array.Finally, you print the result. If the target is found, you display its index; if not, you display "Element not found".
Output:
Element found at index 3
This output shows that the target element 7 was found at index 3 in the array.
Also Read: Top 25+ C Programming Projects for Beginners and Professionals
Now that you have the basic implementation, let's see how you can extend this to find multiple occurrences of an element within the array.
In certain scenarios, you might need to find all occurrences of a specific element in an array. The code below performs a linear search and prints all indices where the target element is found, along with the total number of occurrences.
Here's an example of a program for linear search in C with multiple occurrences:
#include <stdio.h>
void linearSearchMultipleOccurrences(int arr[], int n, int key) {
int count = 0;
printf("Occurrences of key %d found at indices: ", key);
// Traverse the array and check each element
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
printf("%d ", i); // Print index of element
count++; // Increment the count of occurrences
}
}
// If no occurrence is found
if (count == 0) {
printf("Element not found.");
} else {
printf("\nTotal occurrences: %d", count);
}
}
int main() {
int arr[] = { 10, 50, 30, 70, 30, 60, 30, 90, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
// Calling linearSearchMultipleOccurrences function
linearSearchMultipleOccurrences(arr, n, key);
return 0;
}
Explanation:
1. Function (linearSearchMultipleOccurrences): The function takes three parameters: the array arr[], its size n, and the target key to search for.
2. Count and Output: If no occurrences are found, the function prints "Element not found". Otherwise, it prints all the indices where the target is found and the total number of times the element appears in the array.
Output:
Occurrences of key 30 found at indices: 2 4 6 Total occurrences: 3
This output shows that the target element (30) was found at indices 2, 4, and 6 in the array, and it appears 3 times. This program for linear search in C efficiently handles multiple occurrences in the dataset.
Also Read: Difference Between C and Java: Which One Should You Learn?
Having covered multiple occurrences, let’s take a deeper dive into pointer-based linear search, which offers more control over memory.
Linear search using pointers in C directly accesses array elements via pointer arithmetic (arr++), which moves the pointer to the next element in the array. Initially, the pointer points to the first element, and after each comparison, arr++ increments the pointer to the next element.
This allows the search to continue through the array until the target is found or the end of the array is reached. Unlike the index-based approach, which uses arr[i], the pointer method can be more memory-efficient and is especially useful for larger datasets.
Here's an example of a program for linear search in C that uses a function with pointers:
#include <stdio.h>
// Function to perform linear search using pointers
int linearSearch(int *arr, int size, int target) {
// Traverse the array using pointer arithmetic
for (int i = 0; i < size; i++) {
// If the target element is found, return its index
if (*arr == target) {
return i;
}
arr++; // Move the pointer to the next element
}
// If the target element is not found, return -1
return -1;
}
int main() {
int arr[] = {5, 9, 3, 7, 2}; // Array to search in
int size = sizeof(arr) / sizeof(arr[0]); // Calculate size of the array
int target = 7; // Element to search for
// Perform linear search using pointer-based function
int result = linearSearch(arr, size, target);
// Check if the element was found and print the result
if (result == -1) {
printf("Element not found\n");
} else {
printf("Element found at index %d\n", result);
}
return 0;
}
Explanation:
1. When using linearSearch function (Using Pointers):
2. When using the main function:
Output:
Element found at index 3
This output shows that the target element 7 was found at index 3 in the array. Using pointers with the linear search algorithm in C allows direct access to array elements and provides an efficient way to iterate through them.
Also Read: Data Types in C and C++ Explained for Beginners
Next, you will explore how to implement linear search using recursion, which provides an alternative to the traditional iterative approach.
In recursive linear search, each recursive call reduces the problem size by checking one element at a time and then calling the function again with a smaller array (decreasing the size n).
The stack unwinds as each call finishes, returning either the index of the element (if found) or -1 (if not found). Tail recursion can optimize this process, where the recursive call is the last operation in the function.
It potentially reduces memory overhead and improves performance, although it doesn't always match the efficiency of the iterative approach in C.
Here's an example of a program for linear search in C using recursive method:
// C Program to implement linear search using recursion
#include <stdio.h>
int linearSearch(int* arr, int n, int key) {
// Base Case: if there are no elements, return -1
if (n == 0)
return -1;
// If the element at (n - 1) index is equal to key, return (n - 1)
if (arr[n - 1] == key) {
return n - 1;
}
// If element is not at n - 1, call linearSearch for the same array but reducing the size by a single element
// Recursive function reducing array size at each call
return linearSearch(arr, n - 1, key);
}
int main() {
int arr[] = { 10, 50, 30, 70, 80, 60, 20, 90, 40 };
int n = sizeof(arr) / sizeof(int);
int key = 30;
// Calling linearSearch function
int i = linearSearch(arr, n, key);
if (i == -1)
printf("Key Not Found");
else
printf("Key Found at Index: %d", i);
return 0;
}
Explanation:
1. Recursive Function (linearSearch): This function works by checking the last element of the array (arr[n-1]) against the target key.
2. Base Case: When the size (n) becomes 0, the function returns -1, indicating that the element isn't in the array.
3. Recursive Case: The function checks the current last element, and if it doesn't match the target, it makes a recursive call to search the rest of the array.
Output:
Key Found at Index: 2
This output shows that the target element (30) was found at index 2 of the array. The recursive implementation allows you to explore the array in a step-by-step manner, utilizing the call stack for the search process.
Also Read: What Are Storage Classes in C?
After understanding the recursive approach, let’s explore how linear search handles edge cases.
Before starting the search, ensure the array is not empty. If the array is empty, the search should immediately return -1, indicating that the element is not found. Additionally, when searching for an element at the first or last index of the array, keep in mind that:
So, in the worst-case scenario, if the target is at the last index, the algorithm will traverse the entire array before identifying the target.
Once you’ve grasped different types of linear search implementations, let's shift focus to the complexity analysis to evaluate the efficiency of the linear search algorithm.
Complexity analysis helps us understand how linear search performs as the input size increases. It shows how the number of comparisons grows, helping us assess the algorithm's efficiency in different scenarios.
Time complexity explains how quickly the search finishes.
Also Read: Why Is Time Complexity Important: Algorithms, Types & Comparison
Space complexity tells us how much memory the algorithm needs.
In summary, linear search has linear time complexity (O(n)) and constant space complexity (O(1)).
While this makes it simple and effective for small or unsorted datasets, it's not the most efficient choice for larger datasets. Let’s compare linear search with Binary Search and Hashing, which offer better performance for sorted and large datasets.
Here’s a comparison table:
Algorithm | Best Case | Worst Case | Space Complexity |
Linear Search | O(1) | O(n) | O(1) |
O(1) | O(log n) | O(1) | |
O(1) | O(n) (in case of collisions) | O(n) (for hash table storage) |
Also Read: Time and Space Complexity in Machine Learning Explained
Now that you’ve analyzed its complexity, let’s explore the advantages and disadvantages of linear search, so you can better assess when to use it.
Linear search is a simple and versatile algorithm used to find an element in a data structure. It is easy to implement and can be used with both sorted and unsorted data, making it useful in many scenarios. However, its efficiency decreases as the size of the data structure grows, making it less ideal for large datasets.
This table summarizes the main strengths and weaknesses of linear search:
Advantages | Disadvantages |
Simplicity: Easy to understand and implement. No need for complex data structures. | Time Complexity: In the worst case, it requires O(n) time to search, making it inefficient for large datasets. |
Versatility: Can be used with arrays, linked lists, and other sequential structures. | Inefficiency for Large Datasets: As data grows, it becomes slower compared to algorithms like binary search. |
No Preprocessing: Works directly on the given data without needing sorting or additional steps. | Lack of Early Termination: Doesn't stop early once the target is found unless optimized manually. |
Space Efficiency: Uses only O(1) additional space, with no extra memory needed. | Ineffective for Sorted Data: Does not utilize sorted order, so it’s inefficient for sorted arrays. |
Handles Unsorted Data: Works well with unsorted data, checking each element sequentially. | High Comparison Count: Requires potentially n comparisons, even if the target is near the beginning. |
Suitable for Small Data Sets: Ideal for small datasets where more complex search algorithms are unnecessary. | Scalability Issues: Becomes impractical for large-scale applications due to performance limitations. |
Also Read: Sorting in Data Structure: Categories & Types [With Examples]
Now that you understand its strengths and weaknesses, let’s assess your knowledge with a small quiz.
This MCQ challenge evaluates your understanding of linear search in C, including its working principles, time complexity, best and worst-case scenarios, advantages, and optimization techniques.
1. What is the key characteristic of a linear search algorithm?
a) It searches the array by jumping specific intervals
b) It compares each element sequentially until a match is found
c) It requires the array to be sorted before searching
d) It always returns the last occurrence of the target element
2. What is the worst-case time complexity of the linear search algorithm?
a) O(1)
b) O(log n)
c) O(n)
d) O(n²)
3. In which scenario is linear search most efficient?
a) When searching a large, sorted dataset
b) When searching an unsorted dataset with a small number of elements
c) When searching for an element in a binary tree
d) When searching an element in a database
4. What will be the output of the following pseudo code if the key is 30?
Array: {10, 50, 30, 70, 80}
Key: 30
FOR each element in array:
IF element == key THEN
RETURN index
RETURN -1
a) 2
b) 3
c) -1
d) 30
5. Which of the following is true about the space complexity of linear search?
a) It requires additional memory proportional to the input size
b) It requires O(1) additional memory
c) It requires O(n) additional memory
d) It cannot be determined
6. If the target element is the first element in the array, what is the time complexity of linear search?
a) O(1)
b) O(n)
c) O(log n)
d) O(n²)
7. What value is typically returned by a linear search function when the target element is not found?
a) The last index of the array
b) 0
c) -1
d) NULL
8. Which of the following is a disadvantage of the linear search algorithm?
a) It requires sorting before searching
b) It cannot be used for small datasets
c) It is inefficient for large datasets
d) It always finds the element in constant time
9. How does linear search behave in the best-case scenario?
a) The element is found at the first position, requiring only one comparison
b) The element is found at the last position
c) The element is found after scanning half of the elements
d) It performs n comparisons in all cases
10. How can we optimize the linear search algorithm for early termination?
a) Always searching the last element first
b) Sorting the array before searching
c) Returning immediately when the target element is found
d) Using recursion instead of iteration
While tutorials provide a solid foundation, consistent practice and exploring advanced search algorithms will improve coding efficiency.
upGrad’s courses provide hands-on training in C programming and algorithm design, covering searching techniques, loops, and data structures. Master linear search, optimize its efficiency, and build a strong foundation for software development and competitive coding.
Explore upGrad’s courses to elevate your programming skills and become proficient in search algorithms:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
C Program to check Armstrong Number
C Operators Tutorial : An Overview with Types and Examples
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
Explain the array of structures in C language
C Program to Find ASCII Value of a Character
Discovering C Operators: An Overview with Types and Examples!
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
C Enum Type: Definition and Practical Implementation
Evaluation of Arithmetic Expression: An Ultimate Guide
Factorial Program of a Number in C
15 Most Important Features of C Language
Linear search has O(n) time complexity, meaning it checks each element one by one, while binary search has O(log n) time complexity, making it more efficient for sorted arrays.
Linear search can be applied to linked lists by starting from the head node and traversing each node one by one, similar to arrays, until the target element is found.
For large datasets, linear search requires checking each element sequentially, resulting in a significant number of comparisons, making it slower than algorithms that take advantage of sorted data or indexing.
Yes, linear search can be implemented recursively by checking the first element and then recursively calling the function on the rest of the array or list.
Linear search stops immediately once the target element is found, making it an early termination algorithm. However, if it is not optimized, it still checks the remaining elements in its basic form.
If the target element is absent, the algorithm will check all elements and return a value indicating that the element was not found (usually -1).
Linear search uses a fixed amount of space, regardless of the input size, as it only requires a few variables for looping and comparisons, hence the space complexity remains O(1).
Linear search can be optimized by stopping as soon as the target element is found and returning the index, avoiding unnecessary comparisons for the remaining elements.
Yes, linear search can be applied to multi-dimensional arrays by treating them as a flattened one-dimensional array or by using nested loops to traverse each element.
Linear search is not suitable for applications requiring fast data retrieval from large datasets or sorted data, such as databases or search engines, where faster algorithms are preferred.
In the case of duplicates, linear search will return the index of the first occurrence of the target element and does not continue checking for subsequent matches unless modified.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.