C program to search an array element using Pointers.


Problem

Write a C program to search an element from an array at runtime by the user and the result to be displayed on the screen after search. If the searching element is not in an array then, we need to search element is not found.

Solution

An array is used to hold the group of common elements under one name

The array operations are as follows −

  • Insert
  • Delete
  • Search

Algorithm

Refer an algorithm to search the elements into an array with the help of pointers −

Step 1 − Declare and read the number of elements.

Step 2 − Declare and read the array size at runtime.

Step 3 − Input the array elements.

Step 4 − Declare a pointer variable.

Step 5 − Allocate the memory dynamically at runtime.

Step 6 − Enter an element that to be searched.

Step 7 − Check if an element is present in an array by traversing. If an element is found display "Yes", otherwise "No".

Example

Size of array is: 5

The array elements are as follows:

1 2 3 4 5

Enter the element to be searched: 4

The output is as follows −

4 is present in the array

Example

Following is the C program to delete the elements into an array with the help of pointers −

 Live Demo

#include<stdio.h>
int i,l;
int search(int ,int *,int);
int main(){
   int n,m;
   printf("enter the size of array:");
   scanf("%d",&n);
   int a[n];
   printf("enter the elements:
");    for(i=0;i<n;i++){       scanf("%d",&a[i]);    }    printf("enter the element to be searched:");    scanf("%d",&m);    search(n,a,m);    return 0; } int search(int n,int *a,int m){    for(i=0;i<n;i++){       if(m==a[i]){          l=1;          break;       }    }    if(l==1){       printf("%d is present in the array",m);    } else {       printf("%d is not present in the array",m);    } }

Output

When the above program is executed, it produces the following output −

Run 1:
enter the size of array:5
enter the elements:
14
12
11
45
23
enter the element to be searched:11
11 is present in the array
Run 2:
enter the size of array:3
enter the elements:
12
13
14
enter the element to be searched:45
45 is not present in the array

Updated on: 26-Mar-2021

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements