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); } |
This C program defines a function called search_function
that searches for a given element in an array. Here’s a concise explanation of the program:
- Function Definition:
search_function(int *a, int n, int s_element)
- This function takes three parameters:
a
: a pointer to an integer array.n
: the size of the array.s_element
: the element to be searched in the array.
- It iterates through the array using a
for
loop and checks if the current element is equal to thes_element
. - If it finds a match, it returns 1 (true), indicating that the element is present in the array.
- If no match is found after checking all elements, it returns 0 (false).
- This function takes three parameters:
- Main Function:
main()
- The main function begins the execution of the program.
- It declares an array
arr
of size 30, variablesi
(for loop iteration),size
(to store the size of the array), ands_element
(the element to be searched). - The user is prompted to enter the size of the array, followed by the array elements.
- The user is then prompted to enter the element to be searched (
s_element
). - The
search_function
is called with the array, size, and search element, and the result is used to print whether the element is present or not.
- Output:
- The program outputs whether the searched element is present or not in the array.