Mastering Linear Search: Understanding the Basics
LINEAR SEARCH
#include<stdio.h>
int main(){
int i,n,target;
int index=-1;
printf("Enter size of an array: ");
scanf("%d",&n);
int a[n];
printf("Enter the array elements: ");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("The array elements are:\n");
for(i=0;i<n;i++){
printf("%d\n",a[i]);
}
printf("Enter the searching element: ");
scanf("%d",&target);
if(target==a[0]){
printf("%d is found at %dth index",target,index++);
}else if(target==a[1]){
printf("%d is found at %dth index",target,index+=2);
}else if(target==a[2]){
printf("%d is found at %dth index",target,index+=3);
}else if(target==a[3]){
printf("%d is found at %dth index",target,index+=4);
}else if(target==a[4]){
printf("%d is found at %dth index",target,index+=5);
}else{
printf("%d is not found in the entire array",target);
}
}
OUTPUT:
CASE 1:
Enter size of an array: 5
Enter the array elements: 10 20 30 40 50
The array elements are:
10
20
30
40
50
Enter the searching element: 30
30 is found at 2th index
CASE 2:
Enter size of an array: 5
Enter the array elements: 10 20 30 40 50
The array elements are:
10
20
30
40
50
Enter the searching element: 56
56 is not found in the entire array
Comments
Post a Comment