0% found this document useful (0 votes)
2 views

Linear Search

The document presents a Java program that implements a linear search algorithm to find a name in a user-defined string array. It prompts the user to enter the size of the array and the names, then searches for a specified name and outputs its position if found. If the name is not found, it informs the user accordingly.

Uploaded by

98hwkb4rzt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Linear Search

The document presents a Java program that implements a linear search algorithm to find a name in a user-defined string array. It prompts the user to enter the size of the array and the names, then searches for a specified name and outputs its position if found. If the name is not found, it informs the user accordingly.

Uploaded by

98hwkb4rzt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Program to Search in the String by using Linear Search

import java.util.*; //Importing Packages

import java.io.*;

import java.lang.*;

public class Linear_Search //declaring class

{ //opening braces of class

public static void main(String args[]) //declaring main method

{ //opening braces of main method

Scanner pa = new Scanner(System.in); //declaring Scanner class

System.out.println("Enter the size of the array");

int n = pa.nextInt(); //To Store the size of an Array

String a[] = new String [n]; //declaring a String array of Size n

System.out.println("Enter the Names");

for(int i=0;i<n;i++) //Loop to Input values in the Array

a[i] = pa.nextLine();

System.out.println("Enter name to be found");

String s = pa.nextLine(); //Store the name to be found

int f=0,p=0; //Neccessary Variable

for(int i=0;i<n;i++) //Loop to Print Array in Single Line

System.out.print(a[i]+"\t");

if(a[i].equals(s)) //If name is founded in the String

f++; //If Name is founded

p=i+1; //To Store the position of name founded

if(f==0) //If Name is founded

System.out.println("\n"+"Name not found");


else //If Name is not founded

System.out.println("\n"+"Name found at "+p);

} //closing braces of main method

} //closing braces of class

VARIABLE DATA TYPE FUNCTION


n Integer To Store the number
a Integer To Store the Array
i Integer Used as a Local variable
s String To Store the String to be found
f Integer To Check the condition if the name is
founded
p Integer To Store the Position of the name

You might also like