Write a C program to input elements in array and search whether an element exists in array or not. How to search element in array linearly in C programming. Logic to search element in array sequentially in C program.
Example
Input
Input size of array: 10 Input elements in array: 10, 12, 20, 25, 13, 10, 9, 40, 60, 5
Output
Element to search is: 25 Element found at index 3
Required knowledge
Basic Input Output, If else, For loop, Array
Logic to search element in array
There are two searching techniques linear and binary. For simplicity, I am implementing linear search algorithm to search element in array.
Step by step descriptive logic to search element in array using linear search algorithm.
- Input size and elements in array from user. Store it in some variable say
size
andarr
. - Input number to search from user in some variable say
toSearch
. - Define a flag variable as
found = 0
. I have initializedfound
with 0, which means initially I have assumed that searched element does not exists in array. - Run loop from 0 to
size
. Loop structure should look likefor(i=0; i<size; i++)
. - Inside loop check if current array element is equal to searched number or not. Which is
if(arr[i] == toSearch)
then setfound = 1
flag and terminate from loop. Since element is found no need to continue further. - Outside loop
if(found == 1)
then element is found otherwise not.
Program to search element in array
/**
* C program to search element in array
*/
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
/* Input size of array */
printf("Enter size of array: ");
scanf("%d", &size);
/* Input elements of array */
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
/* Assume that element does not exists in array */
found = 0;
for(i=0; i<size; i++)
{
/*
* If element is found in array then raise found flag
* and terminate from loop.
*/
if(arr[i] == toSearch)
{
found = 1;
break;
}
}
/*
* If element is not found in array
*/
if(found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array", toSearch);
}
return 0;
}
Learn more how to search an element in array using pointer.
Output
Enter size of array: 10 Enter elements in array: 10 12 20 25 13 10 9 40 60 5 Enter element to search: 25 25 is found at position 4
Happy coding 😉
Recommended posts
- Array and Matrix programming exercises index.
- C program to find second largest element in an array.
- C program to sort elements of array in ascending order.
- C program to sort even and odd array elements separately.
- C program to left rotate array.
- C program to right rotate array.
- C program to print all unique elements in array.