Linear Search Algorithm,Java Program and Complexity


Linear search also called sequential search is a way for finding a target value within a list. It sequentially checks each element from the list for the target value until a match is found or until all the elements have been searched.

Algorithm

  • Target value search start from the leftmost element of array[] and one by one compare target value with each element of array[]
  • If target value matches with an element, return the index.
  • If target value doesn’t match with any of elements, return -1.

Complexity

  • Best Case Performance O(1)
  • Average Case Performance O(n)
  • Worst Case Performance O(1)

Where O is BiG-O Notation and n is no of element in Array/List.

Java Program for Linear Search of Element

import java.util.Scanner;

class LinearSearch {
	public static void main(String args[]) {
		int c, n, targetValue, array[];

		Scanner in = new Scanner(System.in);
		System.out.println("Enter number of elements");
		n = in.nextInt();
		array = new int[n];

		System.out.println("Enter " + n + " integers");

		for (c = 0; c < n; c++)
			array[c] = in.nextInt();

		System.out.println("Enter target value to find");
		targetValue = in.nextInt();

		for (c = 0; c < n; c++) {
			if (array[c] == targetValue)
			{
				System.out.println(targetValue + " is present at location " + (c + 1) + ".");
				break;
			}
		}
		if (c == n)
			System.out.println(targetValue + " is not present in array.");
	}
}

Output

Enter number of elements
10
Enter 10 integers
2
56
3
7
89
34
78
23
67
13
Enter target value to find
7
7 is present at location 4.

Enter number of elements
7
Enter 7 integers
12
45
34
78
23
87
90
Enter target value to find
32
32 is not present in array.

More

For more DataStructure,Algorithms and Java Programing Test questions and sample code follow below links

Advertisements
Posted in Algorithm, Data Structure, Programming Test, Search | Tagged , , , , , , , ,

Ways to Read Input from Keyboard/User/Console by Java Program


Java Support 4 Ways of  read  input from keyboard:

  • Scanner Class (In java.util package)
  • BufferReader and InputStreamReader (java.io package)
  • DataInputStream (Java.io package)
  • Console Class (Some IDE doesn’t support it For Example : Eclipse)

How Data Accepts from Keyboard ?

For accepting data from keyboard by console we need three objects:

  1. System.in
  2. InputStreamReader
  3. BufferedReader

The data is received in the form of bytes from the keyboard by System.in which is an InputStream object.Then the InputStreamReader reads bytes and decodes them into characters.Then finally BufferedReader object reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

 

InputStreamReader and BufferedReader are classes of java.io package.

Below Java Program showing all four ways of taking user input from console.

 

 

package program.common;

import java.io.BufferedReader;
import java.io.Console;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class UserInputWays {

	public static void main(String[] args) {
		Way1ByScanner();
		System.out.println("=====================================================");
		Way2ByBufferReader();
		System.out.println("=====================================================");
		Way3ByDataStream();
		System.out.println("=====================================================");
		Way4ByConsole();
		System.out.println("=====================================================");
	}

	private static void Way1ByScanner() {
		System.out.println("Way 1 : By Scanner Class");
		Scanner scan = new Scanner(System.in);

		System.out.println("Enter a text string");
		String s = scan.nextLine();
		System.out.println("You entered text string " + s);

		System.out.println("Enter an integer value");
		int a = scan.nextInt();
		System.out.println("You entered integer value " + a);

		System.out.println("Enter a float value");
		float b = scan.nextFloat();
		System.out.println("You entered float value " + b);

	}

	private static void Way2ByBufferReader() {
		System.out.println("Way 2 : By BufferReader and InputStreamReader");
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("Enter a text string");
			String s = br.readLine();
			System.out.println("You entered text string " + s);

			System.out.println("Enter an integer value");
			int a = Integer.parseInt(br.readLine());
			System.out.println("You entered integer value " + a);

			System.out.println("Enter a float value");
			float b = Float.parseFloat(br.readLine());
			System.out.println("You entered float value " + b);

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	private static void Way3ByDataStream() {
		System.out.println("Way 3 : By DataStream");
		try {
			DataInputStream dis = new DataInputStream(System.in);

			System.out.println("Enter a text string");
			String s = dis.readLine();
			System.out.println("You entered text string " + s);

			System.out.println("Enter an integer value");
			int a = dis.readInt();
			System.out.println("You entered integer value " + a);

			System.out.println("Enter a float value");
			float b = dis.readFloat();
			System.out.println("You entered float value " + b);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Eclipse doesn't support Console Class to test that use command prompt
	 */
	private static void Way4ByConsole() {
		System.out.println("Way 4 : By Console Class");
		try
		{
		Console console = System.console();

		System.out.println("Enter a text string");
		String s = console.readLine();
		System.out.println("You entered text string " + s);

		System.out.println("Enter an integer value");
		int a = Integer.parseInt(console.readLine());
		System.out.println("You entered integer value " + a);

		System.out.println("Enter a float value");
		float b = Float.parseFloat(console.readLine());
		System.out.println("You entered float value " + b);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}

}

Output

Way 1 : By Scanner Class
Enter a text string
saurabh Gupta
You entered text string saurabh Gupta
Enter an integer value
35
You entered integer value 35
Enter a float value
80.2
You entered float value 80.2
=====================================================
Way 2 : By BufferReader and InputStreamReader
Enter a text string
Saurabh Gupta
You entered text string Saurabh Gupta
Enter an integer value
35
You entered integer value 35
Enter a float value
80.2
You entered float value 80.2
=====================================================
Way 3 : By DataStream
Enter a text string
Saurabh Gupta
You entered text string Saurabh Gupta
Enter an integer value
35
You entered integer value 859114762
Enter a float value
80.2
You entered float value 4.2004693E-5
=====================================================
Way 4 : By Console Class
Enter a text string
=====================================================
java.lang.NullPointerException
	at program.common.UserInputWays.Way4ByConsole(UserInputWays.java:91)
	at program.common.UserInputWays.main(UserInputWays.java:19)

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Posted in Algorithm, Data Structure, Java, Programming Test | Tagged , , , , , , , | 1 Comment

Fahrenheit To Celsius Java Program


This program is to convert Fahrenheit to Celsius temperature based on user input value. Below is mathematical formula for conversion from Fahrenheit to Celsius temperature .

T = 9*T/5 + 32 where T is temperature on Celsius scale.

import java.util.Scanner;

class FahrenheitToCelsius {
	  public static void main(String[] args) {
	    float temperatue;
	    Scanner in = new Scanner(System.in);      

	    System.out.println("Enter Temperatue in Fahrenheit");
	    temperatue = in.nextInt();

	    temperatue = ((temperatue - 32)*5)/9;

	    System.out.println("Converted Temperatue in Celsius = " + temperatue);
	  }
	}

Outout

Enter Temperatue in Fahrenheit
100
Converted Temperatue in Celsius = 37.77778

Enter Temperatue in Fahrenheit
50
Converted Temperatue in Celsius = 10.0

Enter Temperatue in Fahrenheit
75
Converted Temperatue in Celsius = 23.88889

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Posted in Algorithm, Data Structure, Java, Programming Test | Tagged , | 1 Comment

Floyd Triangle Java Program


This is Java Program to print Floyd triangle of continuous numbers based on inserted users numbers of rows.

import java.util.Scanner;

class FloydTriangle
{
   public static void main(String args[])
   {
      int n, num = 1, c, d;
      Scanner in = new Scanner(System.in);

      System.out.println("Enter the number of rows of floyd's triangle you want");
      n = in.nextInt();

      System.out.println("Floyd's triangle :-");

      for ( c = 1 ; c <= n ; c++ )
      {
         for ( d = 1 ; d <= c ; d++ )
         {
            System.out.print(num+" ");
            num++;
         }

         System.out.println();
      }
   }
}

output

Enter the number of rows of floyd's triangle you want
7
Floyd's triangle :-
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Posted in Algorithm, Data Structure, Java, Programming Test | Tagged | 1 Comment

Multiplication Table Java Program


This Java program is for print Multiplication table of Input Number.

import java.util.Scanner;

class MultiplicationTable
{
   public static void main(String args[])
   {
      int n, c;
      System.out.println("Enter an integer value to display it's multiplication table");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();
      System.out.println("Multiplication table of "+n+" is :-");

      for ( c = 1 ; c <= 10 ; c++ )
         System.out.println(n+"*"+c+" = "+(n*c));
   }
}

Output

Enter an integer value to display it's multiplication table

13
Multiplication table of 13 is :-
13*1 = 13
13*2 = 26
13*3 = 39
13*4 = 52
13*5 = 65
13*6 = 78
13*7 = 91
13*8 = 104
13*9 = 117
13*10 = 130

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Posted in Algorithm, Data Structure, Java, Programming Test | Tagged | 1 Comment

Largest of Three Numbers


This java program is to easily find out largest number in three integers values. But that is not optimize way if numbers are more than that better follow other algorithms.

lass LargestOfThreeNumbers {
	public static void main(String args[]) {
		int x, y, z;

		Scanner in = new Scanner(System.in);
		System.out.println("Please Enter First integer");
		x = in.nextInt();
		System.out.println("Please Enter Second integer");
		y = in.nextInt();
		System.out.println("Please Enter Third integer");
		z = in.nextInt();

		if (x > y && x > z)
			System.out.println("First number is largest.");
		else if (y > x && y > z)
			System.out.println("Second number is largest.");
		else if (z > x && z > y)
			System.out.println("Third number is largest.");
		else
			System.out.println("Entered numbers are not distinct.");
	}
}

Output

Please Enter First integer
10
Please Enter Second integer
20
Please Enter Third integer
5
Second number is largest.

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Posted in Algorithm, Data Structure, Java, Programming Test | Tagged | 1 Comment

Palindrome Java Program


Palindrome Definition

“A String is palindrome if it remains unchanged when reversed.”

For Example : String “dad” is a palindrome as reverse of “dad” is “dad” whereas
“program” is not a palindrome. Some other palindrome strings are “nitin”,”mom”, “madam”, “abcba” etc.

Below is simple Java program to check input String is Palindrom or not.

class Palindrome1 {
	public static void main(String args[]) {
		String original, reverse = "";
		Scanner in = new Scanner(System.in);

		System.out.println("Enter a string to check if it is a palindrome");
		original = in.nextLine();

		int length = original.length();

		for (int i = length - 1; i >= 0; i--)
			reverse = reverse + original.charAt(i);

		if (original.equals(reverse))
			System.out.println("Entered string is a palindrome.");
		else
			System.out.println("Entered string is not a palindrome.");

	}
}

Output

Enter a string to check if it is a palindrome
nitin
Entered string is a palindrome.

Enter a string to check if it is a palindrome
Saurabh
Entered string is not a palindrome.

In above program you find out very simple way to check input string is palindrome but in below program you will see to check palindrome string with minimum number of operations because here dividing text in half size and compare with rest of part of String.

import java.util.*;

class Palindrome2
{
  public static void main(String args[])
  {
    String inputString;
    Scanner in = new Scanner(System.in);

    System.out.println("Enter a string to check if it is a palindrome");
    inputString = in.nextLine();

    int length  = inputString.length();
    int i, begin, end, middle;

    begin  = 0;
    end    = length - 1;
    middle = (begin + end)/2;

    for (i = begin; i <= middle; i++) {
      if (inputString.charAt(begin) == inputString.charAt(end)) {
        begin++;
        end--;
      }
      else {
        break;
      }
    }
    if (i == middle + 1) {
      System.out.println("Entered string is a palindrome.");
    }
    else {
      System.out.println("Entered string is not a palindrome.");
    }
  }
}

Output

Enter a string to check if it is a palindrome
nitin
Entered string is a palindrome.

Enter a string to check if it is a palindrome
Saurabh
Entered string is not a palindrome.

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Posted in Algorithm, Data Structure, Java, Programming Test | Tagged , , , , | 1 Comment

Prime Numbers Java program


Prime Number Definition

                 “A whole number greater than 1 that is divisible only by itself and 1”.
A prime number will always have factors as 1 and itself. A factor is a whole numbers that can be divided evenly into another number. If Number is having more than two factors are called composite numbers.
The number 1 is neither prime nor a composite Number.
Smallest prime number is 2 and others are in sequence as 2,3,5,7,11,13,17,19,13,29  etc…

Benefit

  • prime numbers are very useful in cryptography.
  • The mathematicians used prime numbers to develop new areas of mathematics, like number theory and knot theory, which developers use today.
This java program prints  number of prime numbers as required from the user.
import java.util.*;

class PrimeNumbers
{
   public static void main(String args[])
   {
      int n, status = 1, num = 3;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of prime numbers you want");
      n = in.nextInt();

      if (n &gt;= 1)
      {
         System.out.println("First "+n+" prime numbers are :-");
         System.out.println(2);
      }

      for ( int count = 2 ; count &lt;=n ;  )
      {
         for ( int j = 2 ; j &lt;= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            count++;
         }
         status = 1;
         num++;
      }
   }
}

Output

Enter the number of prime numbers you want
5
First 5 prime numbers are :-
2
3
5
7
11
Enter the number of prime numbers you want

10
First 10 prime numbers are :-
2
3
5
7
11
13
17
19
23
29

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Posted in Algorithm, Data Structure, Java, Programming Test | Tagged , , , , , , , , | 1 Comment

Odd and Even Java Program


This java program finds if a number is odd or even.

If the number is divisible by 2 then it will be even, otherwise it is odd. We use Java modulus operator to find remainder in our program.

class OddOrEvenNumber{
	public static void main(String args[]) {<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
		int x;
		System.out.println("Enter an integer value to check if it is odd or even ");
		Scanner in = new Scanner(System.in);
		x = in.nextInt();

		if (x % 2 == 0)
			System.out.println("You entered an even number.");
		else
			System.out.println("You entered an odd number.");
	}
}

Output

Enter an integer value to check if it is odd or even
16
You entered an even number.

Enter an integer value to check if it is odd or even
125
You entered an odd number.

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Posted in Algorithm, Complexity, Data Structure, Java, Programming Test | Tagged , , | 1 Comment

How to Reverse Number by Java Program?


Here in below program logic you will see how can be reverse number by using multiplication, reminder and division operations.

In this  below program follow steps for reverse number:

  1. Reverse number initialize with zero.
  2. Run loop till number of digits in insert number.
  3. Take reminder of number by mod 10.
  4. Add this reminder value with reverse number .
  5. Multiply this reverse number with 10 .
  6. Divide insert number by 10 and steps 2 to 6 repeat continuously.
import java.util.Scanner;

class ReverseNumber
{
   public static void main(String args[])
   {
      int n, reverse = 0;

      System.out.println("Enter the integer number to reverse");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();

      while( n != 0 )
      {
          reverse = reverse * 10;
          reverse = reverse + n%10;
          n = n/10;
      }

      System.out.println("Reverse of entered integer number is "+reverse);
   }
}

Output

Enter the integer number to reverse
12345
Reverse of entered integer number is 54321

Enter the integer number to reverse

54535251
Reverse of entered integer number is 15253545

 

 

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Posted in Algorithm, Java, Programming Test | Tagged , , | 1 Comment