Wednesday, June 26, 2013

Reversing an Integer

Often, while learning to code in any language (including Java), we come across questions that ask you to reverse an integer. For beginners, it may seem to be a very difficult problem to solve, but actually there is a trick that makes it really easy. The trick is to keep on finding the remainder of the number by dividing it with 10 to extract the digits, and also divide the integer by 10 to reduce it till it doesn't equals zero.
Below is the code written in Java that will give you a better idea:

import java.io.*;
class Reverse{
public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int num, rev=0, rem;
System.out.print("Enter the integer:");
num=Integer.parseInt(br.readLine());
while(num!=0){
rem=num%10;
rev=rev*10+rem;
num/=10;
}
System.out.println(rev);
}
}

Friday, June 21, 2013

Prime Number in Java

A prime number is a natural number greater than 1, and that is divisible only by 1 and itself. Below is a Java program to check if a number is a prime number:

import java.io.*;
class PrimeNumber{
public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int num, i, fact=0;
System.out.print("Enter a number:");
num=Integer.parseInt(br.readLine());
for(i=1;i<=num;i++){
if(n%i==0)
fact++;
}
if(fact==2 && num!=1)
System.out.println(num+" is a prime number.");
else
System.out.println(num+" is not a prime number.");
}
}
 
 

Friday, June 14, 2013

Palindrome Number in Java

A palindromic number is one that remains the same even when its digits are reversed. For example, 121 is a palindrome number because it remains the same even when the digits are reversed.
Below is the Java program that accepts an integer from the user and checks if that number is a palindromic number:

import java.io.*;
class Palindrome{
public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int num, rev;
System.out.print("Enter the integer:");
num=Integer.parseInt(br.readLine());
rev=reverse(num);
if(num==rev)
System.out.println(num+" is a palindrome number.");
else
System.out.println(num+" is not a palindrome number.");
}
public static int reverse(int num){
int i, r=0, rem;
for(i=num;i>0;i/=10){
rem=i%10;
r=r*10+rem;
}
return r;
}
}

Thursday, June 13, 2013

Automorphic Number in Java

An automorphic number is a number whose square ends in the same digits as the number itself.
For example, 25 is an automorphic number because 252 = 625, and 625 ends with 25, which is the number itself. Below is the program written in Java to check if a given integer is an automorphic number:

import java.io.*;
class Automorphic{
public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int num, result;
System.out.print("Enter the integer:");
num=Integer.parseInt(br.readLine());
int countDigits=count(num);
int divisor=(int)Math.pow(10, countDigits);
result=(num*num)%divisor;
if(num==result)
System.out.println(num+" is an automorphic number.");
else
System.out.println(num+" is not an automorphic number.");
}
public static int count(int num){
int i, countDigits=0;
for(i=num;i>0;i/=10)
countDigits++;
return countDigits;
}
}

Tuesday, June 11, 2013

Fibonacci Series in Java

The first two numbers in a Fibonacci series is always 0 and 1. And each subsequent number is the sum of the previous two numbers. This is a very common series program given in ICSE board.
Below is the program written in Java that displays the Fibonacci series for a desired range:

import java.io.*;
class Fibonacci{
public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int range, i, f1=0, f2=1, f3;
System.out.print("Enter the range:");
range=Integer.parseInt(br.readLine());
if(range==1)
System.out.println(f1);
else if(range==2)
System.out.println(f1+"\t"+f2);
else if(range>2){
System.out.print(f1+"\t"+f2);
for(i=3;i<=range;i++){
f3=f1+f2;
System.out.print("\t"+f3);
f1=f2;
f2=f3;
}
System.out.println();
}
else
System.out.println("Range should be positive.");
}
}

Pig Latin Program in Java

Pig Latin is nothing but a language game in which an English word is jumbled according to a simple set of rules. It takes the first consonant, or a consonant cluster (if more than one consonant is found), moves it to the end of the word, and adds "ay" to it.
For example, PIG becomes IGPAY when written in Pig Latin form, and TRUCK becomes UCKTRAY.
Below is the program written in Java that can convert a given English word to its Pig Latin form. This program is very popular in ICSE.
import java.io.*;
class Piglatin{

public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.print("Enter a word:");
String s=br.readLine();
s=s.toUpperCase();
char ch='\u0000';
int index=0;
String str=new String();
outer:
for(int i=0;i<s.length();i++){
ch=s.charAt(i);
switch(ch){
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
index=i;
break outer;
}
}
str=str+s.substring(index)+s.substring(0,index)+"AY";
System.out.println(str);
}
}

Monday, June 10, 2013

Scanner Class in Java

The Scanner class was introduced in JDK1.5. So, make sure you have at least this version installed before actually using it. It is available in java.util package. It can be used to obtain input from console, a file, a String, etc.
The Scanner class splits input into substrings (also known as tokens), which are separated by delimiters. The default delimiter (if not specified) is any white space.
Below is the program written in Java that demonstrates how to input from console (keyboard) using Scanner class:
import java.util.*;
class ScannerDemo{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter an integer:");
int i=sc.nextInt();
System.out.println("You entered "+i);
System.out.print("Enter a real number:");
double d=sc.nextDouble();
System.out.println("You entered "+d);
System.out.print("Enter an boolean value:");
boolean b=sc.nextBoolean();
System.out.println("You entered "+b);
System.out.print("Enter a word:");
String w=sc.next();
System.out.println("You entered "+w);
sc.useDelimiter("\n");
System.out.print("Enter an sentence:");
String s=sc.next();
System.out.println("You entered "+s);
}
}

The useDelimiter() method is used to set the delimiter you want. By default, the Scanner class stops accepting data as soon as it encounters a blank space while accepting input through the keyboard. To change this behavior, we use useDelimiter() method.

Sunday, June 9, 2013

Linear Search in Java

Linear Search is a search technique, in which the key to be searched is compared with each element in the list, until it is found. This technique works even if the list is not sorted. It is considered to be slower than binary search as the size of the input (list) grows.
Below is the code written in Java that demonstrates linear search:

import java.io.*;
class LinearSearch{
public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int a[]={92, 34, 78, 12, 45, 7, 81, 60, 51, 10};
int key, i;
System.out.print("Enter the integer to search:");
key=Integer.parseInt(br.readLine());
for(i=0;i<a.length;i++){
if(key==a[i])
break;
}
if(i==10)
System.out.println(key+" not found");
else
System.out.println(key+" found at index "+i);
}

}

Saturday, June 8, 2013

Binary Search in Java

First thing that we must keep in mind when applying binary search is that it works only on sorted lists. In this search technique, we begin our search from the middle element on the list. 
If the key is found, we stop our search, otherwise, if the key is less than the middle element, the process is repeated in the left half of the list, otherwise, if the key is greater than the middle element, then the process is repeated in the right half of the list.
Below is the code written in Java that implements Binary Search in a one-dimensional array:
import java.io.*;
class BinarySearch{

public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader (isr);
int a[]={7, 10, 12, 34, 45,51, 60, 78, 81, 92};
int key, low=0, high=a.length-1, mid=0;
System.out.print("Enter the integer to search:");        key=Integer.parseInt(br.readLine());
while(low<=high){
mid=(low+high)/2;
if (key==a[mid])
break;
else if(key<a[mid])
high=mid-1;
else
low=mid+1;
}
if(low<=high)
System.out.println(key+" found at index "+mid);
else
System.out.println(key+" not found");
}
}
Binary Search is considered to be much faster than Linear Search, as the size of the input (list) grows.

Wednesday, June 5, 2013

Exchange Selection Sort in Java

In Selection Sort algorithm, we keep on selecting the smallest element (while sorting in ascending order), and place it in its proper position in the list. This process is repeated until the entire list is sorted.
Below is the code written in Java that applies exchange selection sort technique to sort an array of integer elements:

class SelectionSort{
    public static void main(String args[]){
        int a[]={92, 34, 78, 12, 45, 7, 81, 60, 51, 10};
        int i, j, temp, pos, small;
        for(i=0;i<a.length;i++){
            small=a[i];
            pos=i;
            for(j=i+1;j<a.length;j++){
                if(a[j]<small){
                    small=a[j];
                    pos=j;
                }
            }
            temp=a[i];
            a[i]=small;
            a[pos]=temp;
        }
        for(i=0;i<a.length;i++)
            System.out.print(a[i]+"\t");
        System.out.println();
    }


Below is the sequence that demonstrates how the elements are sorted in ascending order, in Exchange Selection Sort:


9234781245781605110


7347812459281605110


7107812459281605134


7101278459281605134


7101234459281605178


7101234459281605178


7101234455181609278


7101234455160819278


7101234455160789281


7101234455160788192


The elements colored green indicates sorted elements. The elements in red are the ones that are compared with each other to see if they need to be swapped.

Bubble Sort in Java

Bubble Sort is an algorithm in which we compare the adjacent elements in a list, and swap them if they are not in proper order. In each iteration, the largest element is placed in its proper position (when sorting in ascending order). The same process is then repeated with the remaining elements. Below is the code written in Java that sorts an array in ascending order, using the bubble sort technique:
class BubbleSort{
    public static void main (String args[]){
        int a[] = {92, 34, 78, 12, 45, 7, 81, 60, 51, 10};
        int i, j, temp;
        for (i = 0; i < a.length; i++){
            for (j = 0; j < a.length-i-1; j++){
                if (a[j] > a[j+1]){
                    temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                }
            }
        }
        for (i = 0; i < a.length; i++)
            System.out.print (a[i] + "\t");
        System.out.println ();
    }
}


Let's see a demonstration of how each iteration takes place in sequence to move the largest element to its proper position. The elements in red denote the adjacent elements which are compared and then swapped (if required):

9234781245781605110


3492781245781605110


3478921245781605110


3478129245781605110


3478124592781605110


3478124579281605110


3478124578192605110


3478124578160925110


3478124578160519210


3478124578160511092
Since 92 was the largest element, it is finally placed in its proper position while sorting in ascending order. This process is repeated with the remaining elements, until it is assured that the entire list is sorted.