INPUT:Array with lower bound(l) and upper bound(u) and key to be searched
OUTPUT: Element is present in the array or not
Data Structure: Single Dimensional Array
STEP 1: START
STEP 2: WHILE(i<=u&&flag==false)
STEP 3: IF(A[i]=KEY) THENSTEP 4: POS=i;FLAG=true;
STEP 5: ENDWHILE
STEP 6: IF(FLAG=TRUE)THEN
STEP 7: PRINT “ELEMENT PRESENT AT,pos
STEP 8: END
Code
C
JAVA
C
#include <stdio.h>
int linearsearch(int);
int a[]={1,5,3,2,1};
int i;
int main()
{
int n,pos=0;
printf("enter the number to be searched ");
scanf("%d",&n);
pos=linearsearch(n);
if(pos==-1)
printf("Element not found ");
else
printf("Element found at location %d",pos);
return 0;
}
int linearsearch(int n){
int flag=0,pos=-1;
while(i<5&&flag==0)
{
if(n==a[i])
{
flag=1;
pos=i;
break;
}
else
i++;
}
return pos;
}
Output
enter the number to be searched 5
Element found at location 1
enter the number to be searched 10
Element not found
JAVA
import java.util.*;
class linearsearch
{
public static void main(){
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER TO BE SEARCHED:");
int n=sc.nextInt();
int a[]={1,2,3,4,6,7,9};
int flag=0;
int i=0;
while(i<a.length&&flag==0)
{
if(n==a[i])
{
flag=1;
}
i++;
}
if(flag==1)
System.out.println("ELEMENT PRESENT");
else
System.out.println("ELEMENT NOT FOUND");
}
}
Pingback: Array Traversal in C