Friday, December 8, 2017

How to multiply two numbers of any digits in Java

This code is implemented and provided by Himanshu from Agra University.

By using this code we can multiply two numbers of any digits. 

Note : Before using this code please create a Java Project in Eclipse IDE and save this class inside 
MultiplicationOfNumbers.java file.

import java.util.Scanner;

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

    System.out.print("Enter first String in integer format :");
    String num1=sc.next();
 
System.out.print("Enter second String in integer format :");
    String num2=sc.next();
   
    // create two objects of string-builder using the data of
    // 'num1' and 'num2' then reverse it and convert into string,
    //  then store it inside string
    String n1 = new StringBuilder(num1).reverse().toString();
    String n2 = new StringBuilder(num2).reverse().toString();

    int[] d = new int[num1.length()+num2.length()];
    for(int i=0; i<n1.length(); i++){
        for(int j=0; j<n2.length(); j++){
            d[i+j] += (n1.charAt(i)-'0') * (n2.charAt(j)-'0');
        }
    }
   
// create object of string-builder class (it is a muttable object)
// in this object we will store the intermediate calculations
    StringBuilder sb = new StringBuilder();
   
    for(int i=0; i<d.length; i++){
        int mod = d[i]%10;
        int carry = d[i]/10;
        if(i+1<d.length){
            d[i+1] += carry;
        }
        sb.insert(0, mod);
    } 
   
    while(sb.charAt(0) == '0' && sb.length()> 1){
      sb.deleteCharAt(0); 
   }
 
  // convert the string-builder into string and
  // store the result in string
  String result = sb.toString();
  System.out.println("Result of multiplication is "+result);
 
  } // end of main
} // end of class

Output of Code :
Enter first String in integer format :200
Enter second String in integer format :900
Result of multiplication is 180000


Saturday, October 14, 2017

Very important question asked in MNC related to String

In many MNC they ask how to reverse the content of String without using loop and methods of String class


Answer : We can reverse the content of String using the following algorithm  

Step#1: Create object of StringBuilder class

Step#2: Store string type data inside object of StringBuilder using append() method

Step#3: Reverse the content of StringBuilder using reverse() method

Step#4: Convert the content of StringBuilder into String using toString() method and store it inside a reference-variable of String

Now, we can show the entire process using a java program 

Note: Create Java project in Eclipse IDE and save this class inside ReverseTheString.java file

public class ReverseTheString
{
public static void main(String[] args)
{
// take a string
 String str = "I am a string";

// Step#1
 StringBuilder s = new StringBuilder();

// Step#2
 s.append(str);

// Step#3
s.reverse();

// Step#4
str = s.toString();

// show the data of string
System.out.println("String after reverse is -> "+str);
}
}

Output of code ===>>>

String after reverse is -> gnirts a ma I


 

Saturday, September 30, 2017

A very important conceptual question frequently asked in MNC's.

Note: Before using this code please create a Java Project in Eclipse IDE and save this code in TestRTP.java file

Please see the output and understand the concept by reading the explanation. Given below this code

import java.util.*;
class Father 
{
public String name = "Satnam";

public static void eating()
{
System.out.println(" is eating fruits");
}

public void drinking()
{
System.out.println(" is drinking coconut water");
}
}

class Son extends Father
{
public String name = "Gurnam";

public static void eating()
{
System.out.println(" is eating pasta");
}

public void drinking()
{
System.out.print(" is drinking mango juice\n");
}
}

public class TestRTP
{
public static void main(String[] args)
{
Father f = new Son(); // assume it is line no-1

System.out.print(f.name); // assume it is line no-2
f.eating(); // assume it is line no-3

System.out.print(f.name);
f.drinking(); // assume it is line no-4
}
}

Output of code =>

Satnam is eating fruits
Satnam is drinking mango juice

Explanation of code =>

Father is a super-class and Son is a subclass. In subclass we are re-defining the static-method and non-static-method of super-class. When a subclass redefine the same non-static-method of super-class, this process is known as method-overriding.

At line-1 we are taking a reference-variable of super-class(ie. father) and assigning the object of subclass (ie. son) into it (this process is known as polymorphic assignment).

At line-2 when we access the variable 'name', the 'name' of father will be printed since the data members (i mean variables) are mainly bound to the type of object rather than the object itself.

The same process will be followed at line-3 when we call a static-method (static-method of super-class will be invoked).

But when we come to line-4 the whole scenario will be changed.
At line-4 the non-static-method of sub-class will be invoked.
Reason, the overridden non-static-method are bound to object rather than the type of object.
So even the reference-variable belongs to super-class the object is of subclass, so in this case the method of subclass (ie. son) will be invoked.

Friday, September 22, 2017

Code by Vasu, Minimum Distance between two words in a paragraph

This code is implemented and provided by Vasu. 

About code : Using this program we can find out the minimum distance between two words inside a paragraph.

Note: Before using this code please create a Java project in Eclipse and save this class inside MinimumDistance.java file.

import java.util.Scanner;

public class MinimumDistance {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in) ;

String para = "We have the BST search and insert operations. "
                         + "We also In the search post and delete operation is discussed. "
                                 + "When we delete a node, there possibilities arise." ;

para = para.toLowerCase();

System.out.println("Enter The two words : ");

String word1 = sc.next() , word2 = sc.next() ;

int index1 = -1 , index2 = -1 , min = Integer.MAX_VALUE;

for (int i = 0; i < para.length() ; i++) {

int count1 = 0 , count2 = 0 ;

for (int j = 0; j < word1.length(); j++) {

if(word1.charAt(j) != para.charAt(i+count1)) {
break ;
}
                                else {
if(count1 == word1.length()-1) {
index1 = i ;
count1 = 0 ;
break ;
}
                                        else {
count1++ ;
}
}
}

for (int j = 0; j < word2.length(); j++) {
if(word2.charAt(j) != para.charAt(i+count2)) {
break ;
}
                                else {
if(count2 == word2.length()-1) {
index2 = i ;
count2 = 0 ;
break ;
}
                                        else {
count2++ ;
}
}
}

if(index2 > index1) {
if(index2-index1 < min) {
min = index2-index1 ;
}
}


}

System.out.println("The Minimum distance between the two words "
                                        +"in the para is : " + min);

}
}

Output of this program =>
Enter The two words :
We
is
The Minimum distance between the two words in the para is : 95

Wednesday, September 20, 2017

Code by Vasu, Tic Tac Toe in Java

This code is implemented and provided by Vasu.

It is a code to play the famous Tic Tac Toe game. When we run this code a GUI will be shown in order to play the game.

Note. Before using this code please create a "Java Project" in Eclipse IDE and save this class inside 
Game.java file

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import java.awt.GridLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Game {

JFrame frame;
JButton[] jButtons = new JButton[9] ;
String[] board = new String[9] ;
int player = 1 ;

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game window = new Game();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});

}

public Game() {
for (int i = 0; i < board.length; i++) {
board[i] = String.valueOf(i) ;
}
initialize();
}

private void initialize() {
frame = new JFrame();
frame.setTitle("Player " + 1 + " turn");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(3, 3, 0, 0));


ActionListener listener = new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent e) {
           if (e.getSource() instanceof JButton) {
            JButton button = (JButton) e.getSource();
            update(button);
           }
       }
   };

for (int i = 0; i < 9 ; i++) {
jButtons[i] = new JButton(String.valueOf(i));
jButtons[i].setFont(new Font("Arial", Font.PLAIN, 40));
jButtons[i].setForeground(new Color(255, 255, 255, 0));
jButtons[i].setFocusPainted(false);
jButtons[i].addActionListener(listener);
frame.getContentPane().add(jButtons[i]);
}

}


public void update(JButton button) {

int i , player_number = 0 ;

if(player%2 != 0) {
player_number = 1 ;
board[Integer.parseInt(button.getText())] = "O" ;
button.setText("O") ;
}else {
player_number = 2 ;
board[Integer.parseInt(button.getText())] = "X" ;
button.setText("X") ;
}


button.setEnabled(false);

i=checkwin();

player++;

if(i == 1) {
 JOptionPane.showMessageDialog(null,  "Player " + player_number +" win" , "YEAH!!",JOptionPane.INFORMATION_MESSAGE);
}else if(i == 0) {
JOptionPane.showMessageDialog(null,  "Match Draw");
}

if(player%2 != 0) {
player_number = 1 ;
}else {
player_number = 2 ;
}

frame.setTitle("Player " + player_number + " turn");

}

public int checkwin() {
if (board[0].equals(board[1]) && board[1].equals(board[2])) {
jButtons[0].setBackground(Color.CYAN);
jButtons[1].setBackground(Color.CYAN);
jButtons[2].setBackground(Color.CYAN);
return 1;
}
else if (board[3].equals(board[4]) && board[4].equals(board[5])) {
jButtons[3].setBackground(Color.CYAN);
jButtons[4].setBackground(Color.CYAN);
jButtons[5].setBackground(Color.CYAN);
return 1;
}
else if (board[6].equals(board[7]) && board[7].equals(board[8])) {
jButtons[6].setBackground(Color.CYAN);
jButtons[7].setBackground(Color.CYAN);
jButtons[8].setBackground(Color.CYAN);
return 1;
}
else if (board[0].equals(board[3]) && board[3].equals(board[6])) {
jButtons[0].setBackground(Color.CYAN);
jButtons[3].setBackground(Color.CYAN);
jButtons[6].setBackground(Color.CYAN);
return 1;
}
else if (board[1].equals(board[4]) && board[4].equals(board[7])) {
jButtons[1].setBackground(Color.CYAN);
jButtons[4].setBackground(Color.CYAN);
jButtons[7].setBackground(Color.CYAN);
return 1;
}
else if (board[2].equals(board[5]) && board[5].equals(board[8])) {
jButtons[2].setBackground(Color.CYAN);
jButtons[5].setBackground(Color.CYAN);
jButtons[8].setBackground(Color.CYAN);
return 1;
}
else if (board[0].equals(board[4]) && board[4].equals(board[8])) {
jButtons[0].setBackground(Color.CYAN);
jButtons[4].setBackground(Color.CYAN);
jButtons[8].setBackground(Color.CYAN);
return 1;
}
else if (board[2].equals(board[4]) && board[4].equals(board[6])) {
jButtons[2].setBackground(Color.CYAN);
jButtons[4].setBackground(Color.CYAN);
jButtons[6].setBackground(Color.CYAN);
return 1;
}
else if (!board[0].equals("0") && !board[1].equals("1")
                 && !board[2].equals("2") && !board[3].equals("3")
                && !board[4].equals("4") && !board[5].equals("5")
                && !board[6].equals("6") && !board[7].equals("7")
               && !board[8].equals("8") )

return 0;
else
return -1;
}


}

Friday, September 15, 2017

Code by Vasu, How to find Derivative of a polynomial



This code is implemented and provided by Vasu

A code to find Derivative of a polynomial

Note: Before using this code please create a java project and save this class inside DerivativePolynomial.java file 


import java.util.Scanner;

public class DerivativePolynomial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the degree : ");
int degree = sc.nextInt();
System.out.println("Enter the " + (degree+1) + " coefficients " );
int[] coeff = new int[degree+1];
for (int i = 0; i < coeff.length; i++) {
coeff[i] = sc.nextInt();
}
int[] derivativeCoeff = new int[degree] ;
for (int i = 0; i < derivativeCoeff.length;  i++) {
derivativeCoeff[i] = coeff[i]*(degree - i);
}
for (int i = 0; i < derivativeCoeff.length; i++) {
System.out.print(derivativeCoeff[i] + "*x^" + (degree - i) );
if(i != derivativeCoeff.length-1 && derivativeCoeff[i+1] > 0  ) {
System.out.print("+");
}
}
}

}

Output of Code =>

Enter the degree : 3
Enter the 4 coefficients 
20
12
10
30
60*x^3+24*x^2+10*x^1

Sunday, August 27, 2017

Very important concept "The Binary Search" by Keshav

This code is implemented and provided by Keshav from Cetpa Infotech.

Binary Search : search an element [ stbs==>String to be search ] over
sorted array of n-elements by repeatedly dividing the search interval in half.
If 'stbs' is found in the array, return the position of element in the array
else return -1.
step 1: initially compare the 'stbs' begin with an interval covering 
the whole array.
if there is only one element in the array, then compare 'stbs' with
element. if it matches, then return 0 as index value. else return -1.
step 2: find the mid element. and compare it with 'stbs'. if matches, return 
mid position 
step 3: else if compareTo() method return -ve value then 'stbs' 
can be match in left half subarray before the mid element.
step 4: else 'stbs' can be match in right half subarray after the mid element.
  
NOTE: 1.Please create a Java project in Eclipse and save this class as 
BinarySearchForString.java
   2.Binary search only works on sorted array.
       Click here to know more about binary search


import java.util.*;
class BinarySearchForString
{
/* lets define a method search() which will be call recursively, this method will
take four arguments, 1st is an array of String, 2nd and 3rd argument will define
an interval and 4th argument will be 'String to be search' [stbs].
*/
static int search(String data[],int i,int j,String stbs)
{
// if (i==j) that means there is only one element in array.
if(i==j){
// lets compare the stbs with array element by calling compareTo()
// method, if match then return the position of element.
if(stbs.compareTo(data[i])==0){
return i;
}
// else return -1. ==> it means element is not present in array.
else{
return -1;
}
}
// if there is more then one element then find the mid position and then
// compare the stbs with mid position element.
else{
// so lets get the mid position.
int mid=(i+j)/2;
/* lets compare the stbs with mid position element.
if matches [means, if compareTo() method return 0 then ]
return mid position.*/
if(stbs.compareTo(data[mid])==0){
return mid;
}
/* if compareTo() method return negative (-ve) value, then 'stbs'
can be match in left half subarray before the mid element i.e.
[ from i to mid-1 ] */
else if(stbs.compareTo(data[mid])<0){
return search(data,i,mid-1,stbs);
}
// else 'stbs' can be match in right half subarray
// after the mid element i.e. [ from mid+1 to j ]
else{
return search(data,mid+1,j,stbs);
}
}
}


public static void main(String[] args)
{
// lets define an array of String
String str[]={"calcutta","delhi","hyderaba","jaipur","mumbai","pune"};
// lets get the number of element in the array.
int n=str.length;

Scanner sc=new Scanner(System.in);
System.out.println();
// now here i am going to show the element present in the array.
for(String s:str)
{
System.out.print(s+"  ");
}

System.out.println("\n");
System.out.print("enter String that to be search:");
String stbs=sc.next();
/* lets call the search() method to find the position of 'stbs'.
this method will return the postion of 'stbs' available inside
the array. else return -1. */
int index=search(str,0,n-1,stbs);
if(index!=-1){
System.out.println("the String is at index: "+index);
}
else{
System.out.println("the String is not availble: "+index);
}
}
}


now lets calculate the Time Complexity.
assume, there is n element in the array. and T(n) be the amount of time required to
find the element [stbs] using above algorithm.

but before this, let analysis the code.
1. if(i==j){
2. if(stbs.compareTo(data[i])==0){
3. return i;
4. }
5. else{
6. return -1;
7. }

from line number 1 to 7, there is one comparison which is done in O(1) time.

8. else{
9. int mid=(i+j)/2; ==> here is 0 comparison ==>mid position can
find in constant time that is O(1) time.

10. if(stbs.compareTo(data[mid])==0){
11.  return mid; ==> here is only one comparision ==>O(1) time.
12. }
13. else if(stbs.compareTo(data[mid])<0)
                        { ==> here is also one comparison
==> that can be done in O(1) time.
14. return search(data,i,mid-1,stbs);==> it takes T(n/2) time.
15. }
16. else{
17. return search(data,mid+1,j,stbs);==> it takes T(n/2) time.
18. }
19. }

overall time is 

T(n) = O(1) ==> if n=1 <== this is best case
(or)
O(1)+O(1)+O(1)+T(n/2) <== this is worst case

so in the worst case, time complexity is  
T(n) = T(n/2)+c, here c means constant time which is used to represent
         [O(1)+O(1)+O(1)]
         after solving this by using substitution approach , 
         we get Time Complexity as O(log n).

Friday, August 25, 2017

Frequently asked interview question on java programming language part Eight (8)

Question: Can you tell me the output of this code. Also justify your answer.

Note: Before using this code please create a Java project inside Eclipse and save this class inside TestOfArray.java file

class TestOfArray {

public static void main(String[] args) {

int[] array1 = {1,2}; // lets assume it is line 1
String[] array2 = {"1","2"}; // lets assume it is line 2
char[] array3 = {'1','2'}; // lets assume it is line 3

System.out.println(array1); // lets assume it is line 4
System.out.println(array2); // lets assume it is line 5
System.out.println(array3); // lets assume it is line 6
System.out.println(array3.toString()); // lets assume it is line 7

}
}

The output of this code will be something like ->

array of int: [I@15db9742
array of string: [Ljava.lang.String;@6d06d69c
array of char: 12


Explanation of this code ->

In Java the arrays are represented as an object, and every object has an address.
The name of array is treated like a reference-variable/object-name.

At line number 1 we are creating an array of int
At line number 2 we are creating an array of string
At line number 3 we are creating an array of string

Now,
Actually println is an overloaded methods of PrintStream class (means, many methods in a class with same name but with different parameters).

list of println() method inside PrintStream class is given below ->

1. public void println();
2. public void println(boolean);
3. public void println(char);
4. public void println(int);
5. public void println(long);
6. public void println(float);
6. public void println(double);
7. public void println(char[]);
8. public void println(java.lang.String);
9. public void println(java.lang.Object);

So, at line number 4 and 5 when we pass array name inside println() method the compiler will convert the address of array into string by using toString() method and then this method "public void println(java.lang.String)" will be called, and it will print the address of array in string format

But, when we pass array of char inside println method at line number 6, the method " public void println(char[])" will be called and it will print the content of array rather than address.

Now, at line number 7 we are explicitly calling toString() method on array of char in order to convert it into string, then in this case the method "public void println(java.lang.String)" will be called and address of array will be printed


Thursday, August 24, 2017

Beautifull Java code for "Tower of Hanoi" problem by Keshav

A code by Keshav, from Cetpa Infotech.


The Tower of Hanoi 

Tower of Hanoi is a mathematical game.
 it consist of 3 rods and different size of disks
and they will in ascending order from top to bottom
which can slide onto any rod.
There is some rules: 
==>only one disk can slide at a time from one rod to another.
==>disks should be in ascending order from top to bottom
==>only top of the disk can slide.

To know more about "Tower of Hanoi" please click on this link want to know more about tower of hanoi

Note: Please create a Java project in Eclipse and save this class as TowerOfHanoi.java file


import java.util.Scanner;
import java.util.InputMismatchException;
public class TowerOfHanoi {

/* 
 lets define a method toh() which will be call recursively. 
 this method will take three arguments. 1st argument will be
 number of disk (nod), 2nd argument will be source rod or 
 can say starting rod, 3rd argument will be middle rod and
 4th argument will be last rod or destination rod.
  
 so it will be like
 toh(number_of_disk,starting_rod,middle_rod,last_rod)
  
 number_of_disk==> nod
  
 note: slide of a disk will be source to destination.
  
 At the end of the program we will see how to calculate 
 time complexity of this program.
 */
static int moves = 0;
static int toh(int nod,String st,String mi,String la)
{
// if ther is only one disk
if(nod==1)
{
System.out.println("Step "+(moves+1)+"==> Move "+st+" to "+la);
moves++;
}
// otherwise
else
{
/* here st means A
    la means C
    mi means B 
*/
 
toh(nod-1,st,la,mi);
/* here st means A
     mi means B
     la means C 
*/
toh(1,st,mi,la);
/* here mi means B
     st means A
     la means C 
*/
toh(nod-1,mi,st,la);
}
return moves;
}
public static void main(String[] args) {
// nod means number_of_disks
int nod;
// lets get the number of disk
Scanner sc=new Scanner(System.in);
System.out.print("enter number of disk to be moved :");
try
{
nod=sc.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("you have given wrong input");
System.out.println("try again");
// lets initialize the nod with 0 and terminate the jvm
nod=0;
System.exit(0);
}
// it indicates starting rod
// let give a name to it as "A"
String start="A";
// it indicates middle rod
// let give a name to it as "B"
String middle="B";
// it indicates last rod
// let give a name to it as "C"
String last="C";
int moves = toh(nod,start,middle,last);
System.out.println("No of moves are "+moves);
}
}
// end of the programe

lets calculate time complexity of this code =>
as we have call 3 methods as follows 
toh(nod-1,st,la,mi);==>it will execute T(n-1) time
toh(1,st,mi,la); ==>it will execute only 1 time
toh(nod-1,mi,st,la);==>it will execute T(n-1) time
where n indicates number_of_disk
so overall time will be
T(n)=T(n-1)+1+T(n-1)=2T(n-1)+1
so the time complexity we will get as O(2^n).


Tuesday, August 22, 2017

One of the most important and frequently asked interview question on pointers

Question: Hey, can you explain the "pointer to a constant" and a "constant pointer".
               Also explain the combo of these two.

Note: Please copy and paste this code in any IDE related to C or C++.
(I have used Dev C++)

Detailed Explanation: 

----------------------------------------------------------------------------  

#include<stdio.h>
int main()
{
int a = 1;
int b = 1;
int c = 1;

// 'p' is a pointer to constant
// means the value which is pointed by pointer 'p' can't be modified
// but address stored inside pointer 'p' can be modified
// so, lets create a pointer to constant 'p' and store address of 'a' inside it
int const *p = &a;

// lets store the address of variable 'b' inside pointer 'p'
p = &b;

// lets modify the value pointed by pointer 'p'
// as we know we can't change the value pointed by pointer 'p'
// this statement will raise a compilation error
*p = 100;  // <= THIS IS A COMPILATION ERROR, so please comment this
         // line before use

// 'q' is a constant pointer 
// means the address which is stored inside pointer 'q' can't be modified
// so, lets create a constant pointer 'q' and store address of 'a' inside it
int *const q = &a;

// lets change the address stored inside pointer 'q'
// as we know we can't change the address which is stored inside pointer 'q'
// this statemnt will raise a compilation error
q = &b;  // <= THIS IS A COMPILATION ERROR, so please comment this
         // line before use

// this statement works fine since value pointed by pointer 'q' can be changed
*q = 100;

// 'r' is a constant pointer as well as pointer to constant 
// means the address which is stored inside pointer 'r' can't be changed
// also the value pointed by pointer 'r' can't be changed
// so, lets create a constant pointer to constant 'r' and store address of 'a'
        // inside it
const int *const r = &a;

// lets change the address stored inside pointer 'q'
// as we know we can't change the address which is stored inside pointer 'r'
// this statemnt will raise a compilation error
r = &a;   // <= THIS IS A COMPILATION ERROR, so please comment this
        // line before use

// lets modify the value pointed by pointer 'r'
// as we know we can't change the value pointed by pointer 'r'
// this statemnt will raise a compilation error
*r = 100;  // <= THIS IS A COMPILATION ERROR, so please comment this
        // line before use

      return 0;
}

----------------------------------------------------------------------------    

Monday, August 21, 2017

Awesome code by MAYANK to convert Number to Word, Non Recursive approach

This code is implemented and provided by Mayank Banga (WW), 
from GBU, Greater Noida.

About this code : By using this code we can translate a number into a word without using recursion

For example 1 will become one
and 120 will become  1 hundred twenty 

Note : Before using this code please create a java project in eclipse and save the 
code inside NumberToString .java file inside src folder  


import java.util.Scanner;

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

/*
                 Three arrays for corresponding String to the number
 one to print values of ones place 
 second to print values of tens place
 third is due to different naming of eleven series 
*/
                String[] ones = { "zero", "one", "two", "three", "four", "five", "six", 
                                         "seven", "eight", "nine" };
String[] tens = { "zero", "ten", "twenty", "thirty", "fourty", "fifety",
                                       "sixty", "seventy", "eighty","ninety" };
String[] teens = { "ten", "eleven", "twelve", "thirteen", "fourteen", 
                                         "fifteen", "sixteen", "seventeen","eighteen", "nineteen" };
                System.out.println("please enter any number below 1,00,00,000");
String num = sc.next();
                int a = num.length();
             
                // applying validation such that number above range will show error
if (a > 9) {
System.err.println("OOPS ! Out of range");
System.err.println("Try again by restarting program");
} else {
//converting String into array of bytes 
byte[] b = num.getBytes();
byte[] d = new byte[a];
/*
since in array b we get corresponding ascii value of String 
like for 0 it is 48 and for 1 it is 49
so to get integer back from ascii value array d is used and 
in below for loop we retrieve back the int value from ascii codes
and here array is reversed as we will be decreasing size of array
from end point we will read one value and print corresponding
                        string for it as we do in normal life we read a number from left 
                        to right
*/
for (int i = 0; i < a; i++) {
d[a - i - 1] = (byte) (b[i] - 48);
}
//performing operations regarding to size
while (a != 0) {
if (a == 1) {
System.out.print(ones[d[a - 1]] + " ");
a = a - 1;
} else if (a == 2) {
if (d[a - 1] == 1) {
System.out.print(teens[d[a - 2]] + " ");
a = a - 2;
//here size was decreased by 2 because in 
//case of teens two digit are read as single
} else if (d[a - 1] == 0) {
a = a - 1;
if (d[a - 1] == 0) {
a = a - 1;
}
} else {
System.out.print(tens[d[a - 1]] + " ");
if (d[a - 2] == 0) {
a = a - 2;
} else {
a = a - 1;
}
}
} else if (a == 3) {
if (d[a - 1] == 0) {
a = a - 1;
} else {
System.out.print(ones[d[a - 1]] 
 + " hundred ");
a = a - 1;
}
} else {
if (d[a - 1] == 0) {
a = a - 1;
// to discard 0 that comes on first place 
//as their is no significance of 0 at starting
} else if (a % 2 == 0) {
System.out.print(ones[d[a - 1]]);
if (a == 4) {
System.out.print(" thousand ");
} else if (a == 6) {
System.out.print(" lakh ");
} else if (a == 8) {
System.out.print(" crore ");
}
a = a - 1;
} else if (a % 2 == 1) {
if (d[a - 1] == 1) {
System.out.print(teens[d[a - 2]]);
} else {
System.out.print(tens[d[a - 1]] 
  + " " + ones[d[a - 2]]);
}
if (a == 5) {
System.out.print(" thousand ");
} else if (a == 7) {
System.out.print(" lakh ");
} else if (a == 9) {
System.out.print(" crore ");
}
a = a - 2;
}
}
}
}
}
}

Sunday, August 20, 2017

Awesome code by VASU to convert Number into Words

This code is implemented and provided by Vasu, from MAIT, Delhi.

About this code : By using this code we can translate a number into a word.

For example 1 will become one
and 120 will become  1 hundred twenty 

Note : This code is based on recursion. 
I will post a non recursive approach to do the same thing very soon.
Till then enjoy this code.

Note : Before using this code please create a java project in eclipse and save the 
code inside Conversion.java file inside src folder  

import java.util.Scanner;

// Create a class consisting of main method and a calculate function
public class Conversion {
// Array of numbers for units place
static String[] unit = {"" , "one" , "two" , "three" , "four" , "five" , "six" , "seven" , 
                                       "eight" , "nine" , "ten" , "eleven" , "twelve" , "thirteen" , 
                                       "fourteen" , "fifteen" , "sixteen" , "seventeen" ,
                                       "eighteen","nineteen"} ;
// Array of numbers for tens place
static String[] tens = {"" , "ten" , "twenty" , "thirty" , "forty" , "fifty", "sixty" , 
                                        "seventy" ,"eighty" , "ninety" } ;

public static void main(String[] args) {
// Create object of Scanner Class
Scanner sc = new Scanner(System.in) ;
// Get Input From User
System.out.print("Enter the number : ");
int number = sc.nextInt() ;
// Show the Output to the user
System.out.println("Number in words : " + calculate(number)); 
}
public static String calculate(int n) {
// Create some cases to define range of the input number
if(n < 20) {
// Directly return the string corresponding to the number
return unit[n];  
}

else if(n < 100) {
return tens[n/10] + " " + unit[n%10];
}
                else if(n < 1000) {
// Apply recursion by converting the sub integer to actual integer
return unit[n/100] + " hundred " + calculate(n%100);  
}
                else if(n < 100000) {
// For numbers in thousands
return calculate(n/1000) + " thousand " + calculate(n%1000) ;  
}
                else if(n < 10000000) {
// For number in lakhs 
return calculate(n/100000) + " lakhs " + calculate(n%100000) ; 
}
                 else if(n < 1000000000) {
// For number in crore 
return calculate(n/10000000) + " crore " + calculate(n%10000000) ; 
}
               else {
return "Number Not In The Range ! Please Try Again" ;
}
}
}