In this tutorial, we will write a program to search an element in an array in C. There are various ways or algorithms to search an element in an array, we will use linear search.
Before going further, you should have knowledge of the following topics in C programming.
Explanation:
We will create a program that will take an array element from the user. Then the user will enter an element that needed to be searched. Then the searching will be applied (shown in the program below).
If the element is present in an array it will display found else display not found.
C Program to Search an Element in an Array
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 33 34 35 36 37 38 39 | //C Program to Search an Element in an Array #include <stdio.h> int main() { int arr[30], arr_size, i, s_element, flag = 0; printf("Enter the size of an array: "); scanf("%d", &arr_size); printf("Enter %d elements in an array:\n", arr_size); for (i = 0; i < arr_size; i++) { scanf("%d", &arr[i]); } printf("\nEnter the element to be searched: "); scanf("%d", &s_element); for (i = 0; i < arr_size; i++) { if (arr[i] == s_element) { flag = 1; break; } } if (flag == 1) { printf("Element %d is found at the position %d.", s_element, i + 1); } else { printf("Element %d is not found.", s_element); } return 0; } |
Output:
Enter the size of an array: 5
Enter 5 elements in an array:
12 55 89 2 67
Enter the element to be searched: 89
Element 89 is found at the position 3.
C Program to search an element in an array using Pointers
A separate function( search_function()
) will be created where the array pointer will be declared and the searched element along with the size of an array will be passed. The function will return 1 if any element matches with the searched element otherwise it will return 0.
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 33 34 35 36 37 38 39 40 | #include <stdio.h> int search_function(int *a, int n, int s_element) { int i; for (i = 0; i < n; i++) { if (a[i] == s_element) { return 1; } } return 0; } int main() { int arr[30], i, size, s_element; printf("Enter the size of an array: "); scanf("%d", &size); printf("Enter %d elements of an array:\n", size); for (i = 0; i < size; i++) { scanf("%d", &arr[i]); } printf("\nEnter the element to be searched: "); scanf("%d", &s_element); if (search_function(arr, size, s_element)) printf("Searched element %d is present.", s_element); else printf("Searched element %d is NOT present.", s_element); } |
Output:
Enter the size of an array: 7
Enter 7 elements of an array:
5
12
55
78
1
63
29
Enter the element to be searched: 78
Searched element 78 is present.