Ticker

6/recent/ticker-posts

Header Ads Widget

Linear search in an array - bigfootcode

Linear search in an array - bigfootcode

Introduction
In this tutorial you will learn  how to search an array ,how to create a array and how to display array in one single program.
Linear search in an array - bigfootcode


Theory

In this program we first declare the all the variables required for storing, searching, and printing on the screen.

Then we put a message on a screen that is used to declare the size of an array after that we use that size input by the user in a loop and using for loop we take all the element of array from user.

Afterwards we print all the element of array to the user and then user screen will be print a
message what is user so that the reading that user can input a number to be searched for in an array.
Receiving that number we initialise another group which can compare that number with another element of that array when it matches with that it display the index where it is present, inside the loop we also have if statement full comparing number.

Now let us see how the program will look like and then we see the output of it.

Q) write a program to search an linear array ?
Sol

import java.util.Scanner ;
public class Main {
 public static void main(String[] args) {
 

int A[],size,num;
Scanner in = new Scanner(System.in);
System.out.print( " enter size of array : ");
  size = in.nextInt();   
    A= new int[size]; 

for(int i=0;i<size;i++)
{
System.out.print("enter element "+ (i+1) + " ");
A[i]= in.nextInt();
}
for(int i=0;i<size;i++)
{
System.out.print(A[i]);

}
System.out.printf("enter the number to search :");

num= in.nextInt();
for(int i=0;i<size;i++)
{ if(A[i]==num)
{System.out.printf("number found at index : " + (i+1));
break;}
else
break;
}
 }
}



Now see the output

Output:



enter size of array : 5
enter element 1 1
enter element 2 2
enter element 3 3
enter element 4 4
enter element 5 5
12345enter the number to search :3
number found at index : 3




Post a Comment

0 Comments