C program to search for an element in an array using pointers
In this post, you will learn how to write a C program to search for an element in an array using pointers.
In C programming, array is a data structure that stores a sequential collection of elements that are of same type and a fixed size. We can perform various operations on array elements, like filtering, sorting, searching, and performing mathematical operations. Array is the simplest data structure, allowing one to retrieve each element randomly. It provides a way to access elements using index values.
In C, the pointer helps us to perform many tasks. Pointers are variables that store the address of other variables instead of their value. We can use this address to access the value of the variable through its pointer. We use the symbol "*" infront of the pointer variable name to access the value of variable to which the pointer is pointing.
Algorithm
- Input size of array.
- Input the array elements
- Declare Pointer variable
- Enter an element that has to be searched for
- Check the presence of element in the array
C Program to search for an element in an array using pointers and while loop
The given C program search the entered element into an array with the help of pointers.
#include <stdio.h>
int main() {
int n, target;
printf("Enter the size of array: ");
scanf("%d",&n);
int arr[n];
printf("Enter the elements: ");
for(int i=0;i<n;i++){
scanf("%d",&arr[i]);
}
// Element to search for
printf("Enter the element to be searched: ");
scanf("%d",&target);
int *ptr = arr;
// Search for the element using pointers
while (ptr < arr + n) {
if (*ptr == target) {
printf("Element %d is present at index %ld.", target, ptr - arr);
break;
}
ptr++;
}
if (ptr == arr + n) {
printf("Element %d is not present in the array.", target);
}
return 0;
}
Output of the above code:
Enter the size of array: 5
Enter the elements: 32 12 66 49 83
Enter the element to be searched: 49
Element 49 is present at index 3.
Related Articles
Convert double to int JavaAverage of two numbers in C
Swapping of two numbers in C using pointers
Armstrong number in C using function
Binary to decimal C program
Sum of array elements in C
Random number generator in C
Factorial program in c using while loop
Student mark sheet program in C
C program to sort names in alphabetical order
C program to find largest number in an array
Print first 10 natural numbers using while loop in C
Simple calculator program in C
C program for simple interest
Swap two numbers without using third variable in C
Radix sort program in C
Bit stuffing program in C
Bubble sort program in C
Decimal to hexadecimal in C
Hexadecimal to decimal in C
Quick sort program in C