C PROGRAM
Program for Linear search |Data Structure in C|
Introduction
Searching for an element in an array is a fundamental operation in computer science. Linear Search is one of the simplest search algorithms. This C program demonstrates the implementation of Linear Search, providing insights into how it works and its practical applications.
Code
#include<stdio.h>
#include<conio.h>
void main() {
int a[20], n, i, item;
clrscr();
// Input
printf("How many elements do you want to enter: ");
scanf("%d", &n);
printf("Enter the elements: ");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
// Searching
printf("Enter the element to be searched: ");
scanf("%d", &item);
for (i = 0; i < n; i++) {
if (item == a[i]) {
printf("%d found at position %d", item, i + 1);
break;
}
}
// Output if item is not found
if (i == n)
printf("Item %d not found in the array", item);
getch();
}
Output
How many elements do you want to enter: 8
Enter the elements: 12 34 56 78 90 23 45 67
Enter the element to be searched: 23
23 found at position 6
In this example, the user inputs eight elements (12, 34, 56, 78, 90, 23, 45, 67) into the array. The program then searches for the element 23 using Linear Search and successfully finds it at position 6.
You can try running the program with different sets of elements and search for various items to observe how Linear Search efficiently locates elements in an array. The output will indicate the position of the found element or inform you if the item is not present in the array.
Explanation
1. Header Files:
The program includes the standard input/output header <stdio.h> and the console input/output header <conio.h>.
2. Main Function:
The main function serves as the entry point of the program.
3. Input:
Users input the number of elements and the array elements.
4. Linear Search Algorithm:
The program employs the Linear Search algorithm to find the specified element in the array.
It iterates through each element of the array and compares it with the target element.
5. Output:
The program outputs the position of the found element or a message indicating that the item was not found.
Advantages of Linear Search
1. Simplicity:
Linear Search is straightforward and easy to implement.
2. Works on Unsorted Data:
Unlike some other search algorithms, Linear Search works on both sorted and unsorted arrays.
Conclusion
This C program provides a practical example of implementing Linear Search, a simple yet effective algorithm for finding elements in an array. Understanding Linear Search is essential as it forms the basis for more complex search algorithms.
Feel free to run the program with different sets of elements and search for various items to observe how Linear Search efficiently locates elements in an array. This example serves as a valuable introduction to the Linear Search algorithm in C. Happy coding!
Post a Comment
0 Comments