In this tutorial you will learn about the C Program to Implement Linear Search and its application with practical example.
C Program to Implement Linear Search
In this tutorial, we will learn to create a C program that will do Implement Linear Search using C programming.
Prerequisites
Before proceeding with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- Conditional statement in C Programming.
- Creating and Using the user-defined function in C programming.
Implement Linear Search
In every programming language, the sorting of data is a very important factor. Sorting works are done mainly with the techniques available in C Language. Many different techniques for sorting are available to work.
But the data structure work is incomplete without the searching of the data. In today’s tutorial, we will Implement the Linear Search in the array to find the element in the array.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declare the variables for the program. 2. Taking the input array in sorte format. 3. Implement the Linear Search for the element. 4. Print the Result. 5. End the program. |
Program to Implement Linear Search
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <stdio.h> int main() { //declaring the variable for the program int array[100], search, c, n; //taking input from the user number of elements of the array printf("Enter number of elements in array\n"); scanf("%d", &n); //taking input from the user elements of the array printf("Enter %d integer(s)\n", n); for (c = 0; c < n; c++) scanf("%d", &array[c]); //taking input number to search in array printf("Enter a number to search\n"); scanf("%d", &search); for (c = 0; c < n; c++) { if (array[c] == search) /* If required element is found */ { //printing if in array printf("%d is present at location %d.\n", search, c+1); break; } } if (c == n) //printing if not in array printf("%d isn't present in the array.\n", search); return 0; } |
Output:-
In the above program, we have first declared and initialized a set of variables required in the program.
- search = it will hold the size of an array.
- array[100]= it will hold the elements in an array.
Input from the user for.
Taking input number for.
Printing the output.