// Write a c program to search element in array.
#include<stdio.h>
#include<stdbool.h>
bool isFound(int arr[], int key, int n){
for(int i = 0; i < n; i++){
if(arr[i] == key){
return true;
}
}
return false;
}
int main(){
int n;
printf("Enter the size of the array : ");
scanf("%d", &n);
int array[n];
printf("Enter the element in the array : ");
for(int i = 0; i < n; i++){
scanf("%d", &array[i]);
}
int key;
printf("Enter the searching key : ");
scanf("%d", &key);
if(isFound(array, key, n)){
printf("Element Found");
}else{
printf("Element not found");
}
return 0;
}
#include<stdio.h>
‘#include<stdio.h>’ is preprocessor directive which include the standard library for using the input/output. There are using the printf() and scanf() function respectively input and output.
#include<stdbool.h>
‘#include<stdbool.h>’ is preprocessor directive which include the standard library for bool datatypes. It allows us to use the bool datatype in our program, and provide the bool and true and false keyword used for increase the readability the program and write the expressive code.
// isFound function
bool isFound(int arr[], int key, int n){
for(int i = 0; i < n; i++){
if(arr[i] == key){
return true;
}
}
return false;
}
The above isFound() function which return type is bool, this function only return the true or false. The isFound() function return true if the given key/element is present in the array otherwise return the false. In this function compare every element to key. Key found in the element return true.
// main function
int main(){
int n;
printf("Enter the size of the array : ");
scanf("%d", &n);
int array[n];
printf("Enter the element in the array : ");
for(int i = 0; i < n; i++){
scanf("%d", &array[i]);
}
int key;
printf("Enter the searching key : ");
scanf("%d", &key);
if(isFound(array, key, n)){
printf("Element Found");
}else{
printf("Element not found");
}
return 0;
}
The ‘main()’ function is the entry point the program, every program should be start here. The function takes user input for an array and key, and the size of the array, and checks if the key is present in the array then print “element found” otherwise print “element not found”.
Comments
Oops!