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.

#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:

  1. 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 the s_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).
  2. Main Function: main()
    • The main function begins the execution of the program.
    • It declares an array arr of size 30, variables i (for loop iteration), size (to store the size of the array), and s_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.
  3. Output:
    • The program outputs whether the searched element is present or not in the array.