C Program to Find Whether an Element Exists in an Array
Write a C program to find whether an element exists in an array.
- Takes input for the number of elements and stores them in an array.
- Accepts a key value to search within the array.
- Traverses the array using a loop to check if the key exists.
- Prints whether the key was found or not based on the search result.
Example : pgm.c
#include <stdio.h> int main() { int n, arr[100], key, found = 0; // Input array size printf("Enter the number of elements: "); scanf("%d", &n); // Input array elements printf("Enter %d elements:\n", n); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } // Input element to search printf("Enter the element to search: "); scanf("%d", &key); // Search the element for (int i = 0; i < n; i++) { if (arr[i] == key) { found = 1; break; } } // Output result if (found) printf("%d exists in the array.\n", key); else printf("%d does not exist in the array.\n", key); return 0; }
Output:
Enter the number of elements: 4
Enter 4 elements:
10
23
7
10
Enter the element to search: 10
10 exists in the array.
Enter 4 elements:
10
23
7
10
Enter the element to search: 10
10 exists in the array.