In this tutorial you will learn about the C Program to Search for Element in an Array. and its application with practical example.
C Program to Search for Element in an Array.
In this tutorial, we will learn to create a C program that will Search for Element in an Array Using C programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C programming.
- Arithmetic operations in C Programming.
Search for Element in an Array.
In this program, First, we will first take the size of the array from the user. Then we will take the elements of the array from the user. Then we will take the element to search in the array. After that, we will search that element in the array. Then we will print the result element with its position to the user.
With the help of this program, we can be Search for Element in an Array.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
/* C Program to Search for an Element in an Array */ #include <stdio.h> #define MAX_SIZE 100 // Maximum array size int main() { //declaring the required variables for the program. int arr[MAX_SIZE]; int size, i, toSearch, found; //i = it wwill hold the integer value for the program. //size = it wwill hold the integer value for the program. /* Taking the Input size of array */ printf("Enter size of array: "); scanf("%d", &size); /* Taking the Input elements of array */ printf("Enter elements in array: "); for(i=0; i<size; i++) { scanf("%d", &arr[i]); } // Taking the element to search in the array. printf("\nEnter element to search: "); scanf("%d", &toSearch); /* Assume that element does not exist 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) { //Printing the output of the program. printf("\n%d is found at position %d", toSearch, i + 1); } else { //Printing the output of the program. printf("\n%d is not found in the array", toSearch); } return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- arr[] = it will hold the integer value.
- i = it will hold the integer value.
- size = it will hold the integer value.
- found = it will hold the integer value.
Taking the size of the array and the elements.
Program Code to find the element in the array.
Printing output of the program.