Question
Search for an element input by the user in a given (array for Java/ List for Python) using Linear search.
Enter size of list:5
Enter element in List:
1:10
2:20
3:30
4:40
5:50
Elements in given list:
[10, 20, 30, 40, 50]
Enter Element to be searched:30
Element is available at index: 3
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class linearSearchInGivenArray
{
public static void main(String args[])
{
/* Initialize array */
int [] arr;
int size=0,i=0,numberToBeSearched=0;
boolean flag=false;
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array:");
size = sc.nextInt();
arr=new int[size];
System.out.println("Enter numbers in array:");
for(i=0;i< size;i++)
{
System.out.print((i+1)+":");
arr[i]=sc.nextInt();
}
System.out.println("Elements Entered in given array:");
for(i=0;i< size;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.println("Enter the Element to be Searched:");
numberToBeSearched=sc.nextInt();
for(i=0;i< size;i++)
{
if(arr[i]==numberToBeSearched)
{
System.out.println(numberToBeSearched+" is found in index: "+(i+1));
flag=true;
break;
}
}
if(flag==false)
{
System.out.println(numberToBeSearched+ " not found in given array!!!");
}
}
}
Python
li=[]
size=int(input("Enter size of list:"))
print("Enter elements in list:")
for i in range(0,size):
print((i+1),end=":")
li.append(int(input()))
print("Elements entered in given List:")
print(li)
numberFound=False
numberToBeSearched=int(input("Enter the number to be searched:"))
for i in range(0,size):
if(li[i]==numberToBeSearched):
print(numberToBeSearched,"is found at index:",(i+1))
numberFound=True
break
if(numberFound==False):
print(numberToBeSearched,"not found in given List")