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.
#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
forloop 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
arrof 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_functionis 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.