In this article, we are going to learn how to search elements in array using pointers in c. We are asking the user to enter the size of the array and take the input elements of array elements and search elements in the array.
1. C program to search an element in array using pointers
In this example, we are taking inputs from users for the array elements, and then the user is providing which number they want to search. We are iterating over this array to find the match for the required element.
#include <stdio.h>
#define SIZE 100
int main()
{
int arr[SIZE];
int size;
int ElementToSearch;
bool elementFound;
int *StartIndex = arr;
printf("Please enter size of array(max 100): ");
scanf("%d", &size);
printf("Please enter elements of array:\n");
for (int i = 0; i < size; i++)
{
scanf("%d", (StartIndex + i));
}
printf("Please enter element which you want to Search: ");
scanf("%d", &ElementToSearch);
StartIndex = arr;
int * arrEnd = (arr + size - 1);
while(StartIndex <= arrEnd && *StartIndex != ElementToSearch)
StartIndex++;
if(StartIndex <= arrEnd)
elementFound = true;
else
elementFound = false;
if(elementFound == false)
printf("The element you requested, does not exists in array.");
else
printf("The element exists in the array.");
return 0;
}
Output
Please enter elements of array:
1
2
3
4
5
Please enter element which you want to Search: 3
The element exists in the array.
2. C program to search an element in array using pointers
In this example, We have to define a function to search the element of the array to make the code reusable.
#include <stdio.h>
#define SIZE 100
int searchElement(int * arr, int size, int ElementToSearch)
{
int index = 0;
int * arrEnd = (arr + size - 1);
while(arr <= arrEnd && *arr != ElementToSearch)
{
arr++;
index++;
}
if(arr <= arrEnd)
return index;
return -1;
}
int main()
{
int arr[SIZE];
int size;
int ElementToSearch, Index;
int *StartIndex = arr;
printf("Please enter size of array(max 100): ");
scanf("%d", &size);
printf("Please enter elements of array:\n");
for (int i = 0; i < size; i++)
{
scanf("%d", (StartIndex + i));
}
printf("Please enter element which you want to Search: ");
scanf("%d", &ElementToSearch);
StartIndex = arr;
Index = searchElement(StartIndex, size, ElementToSearch);
if(Index == -1)
printf("The element you requested, does not exists in array.");
else
printf("The element exists in the array at position %d.",Index+1);
return 0;
}
Output
Please enter size of array(max 100): 5
Please enter elements of array:
1
2
3
4
5
Please enter element which you want to Search: 3
The element exists in the array at position 3.
Please enter elements of array:
1
2
3
4
5
Please enter element which you want to Search: 7
The element you requested, does not exists in array.