Array Exercises
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.
Required knowledge
Basic C programming, If else, c-Arrays, C Loops
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 and arr.
- Input number to search from user in some variable say toSearch.
- Define a flag variable as found = 0. I have initialized found 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 like for(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 set found = 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#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; }