PROBLEM STATEMENT
Searching an Array
Write a C program to search for an element ‘a’ in the array. (Linear Search)
Input Format:
Input consists of n+2 integers. The first integer corresponds to ‘n’ , the size of the array. The next ‘n’ integers correspond to the elements in the array. The last integer corresponds to ‘a’, the element to be searched.
Assume that the maximum size of the array is 20.
Assume that the maximum size of the array is 20.
Output Format:
Sample Input 1:
5
2
3
6
8
1
6
Sample Output 1:
6 is present in the array
Sample Input 2:
5
2
3
6
8
1
9
Sample Output 2:
9 is not present in the array
SOLUTION
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,arr[21],search,i,flag=0;
scanf("%d",&n);
//fill array with elements
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
//get search element
scanf("%d",&search);
//If search element matches any of array element make flag=1 and break the loop, since //we found the element. If not found, flag is set to 0 by default in the beginning.
for(i=0;i<n;i++){
if(search==arr[i]){
flag=1;
break;
}
}
//if flag =1 , we found it else we didn't. Print it using ternary operator. or if-else.
flag==1?printf("%d is present in the array",search):printf("%d is not present in the array",search);
return 0;
}
thnx
ReplyDelete