Monday, 29 June 2015

Java program for binary search

import java.util.Scanner;

class BinarySearch
{
  public static void main(String args[])
  {
    int c, first, last, middle, n, search, 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 value to find");
    search = in.nextInt();

    first  = 0;
    last   = n - 1;
    middle = (first + last)/2;

    while( first <= last )
    {
      if ( array[middle] < search )
        first = middle + 1;  
      else if ( array[middle] == search )
      {
        System.out.println(search + " found at location " + (middle + 1) + ".");
        break;
      }
      else
         last = middle - 1;

      middle = (first + last)/2;
   }
   if ( first > last )
      System.out.println(search + " is not present in the list.\n");
  }
}

Saturday, 20 June 2015

Java program for linear search

import java.util.Scanner;
class LinearSearch
{
  public static void main(String args[])
  {
    int c, n, search, 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 value to find");
    search = in.nextInt();

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

Tuesday, 2 June 2015

Java program to find factorial

import java.util.Scanner;
class Factorial
{
   public static void main(String args[])
   {
      int n, c, fact = 1;

      System.out.println("Enter an integer to calculate it's factorial");
      Scanner in = new Scanner(System.in);

      n = in.nextInt();

      if ( n < 0 )
         System.out.println("Number should be non-negative.");
      else
      {
         for ( c = 1 ; c <= n ; c++ )
            fact = fact*c;

         System.out.println("Factorial of "+n+" is = "+fact);
      }
   }
}

Monday, 1 June 2015

Java program to generate random numbers

import java.util.*;
class RandomNumbers {
  public static void main(String[] args) {
    int c;
    Random t = new Random();

    // random integers in [0, 100]

    for (c = 1; c <= 10; c++) {
      System.out.println(t.nextInt(100));
    }
  }
}