| 1. |
Write a program to input a single dimensional array of 20 integers and search for an integervalue input by the user in an array by using Linear Search Technique. If found display “Search Successful” otherwise display “Search Unsuccessful”. |
Answer» Solution:This is written in Java. import java.util.*; public class LinearSearch { public STATIC void main(STRING[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter 20 elements."); INT a[]=new int[20]; for(int i=0;i<20;i++){ System.out.print(">> "); a[i]=sc.nextInt(); } System.out.print("Enter the number you are searching for: "); int x=sc.nextInt(); sc.close(); boolean found=false; for(int y:a){ if(y==x) { found=true; break; } } if(found) System.out.println("Search Successful. Element found."); else System.out.println("Search UNSUCCESSFUL. Element not found."); } } We assume that the element is not in the LIST (found = false). Now, we will loop through array elements and check if the element is present or not. If true, assign found = true and break the loop. At last, check if found == true. If true, "search successful" or else, "search unsuccessful". |
|