Friday, 20 May 2016

Digital Clock Using Thread in JAVA

Digital Clock Using Thread in JAVA

this given example is display digital clock for user it takes time from working system and display it on the JFrame with the help of thread and swing package.

Program:

import java.util.*;
import java.text.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class ClockScreen extends JFrame{
private JLabel timeString,lbl_digi;
public JButton start;
Thread t;
public ClockScreen(Thread t){
this.setTitle("Digital Clock");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(200,130);
this.setLayout(null);
this.setLocation(GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().x-this.getWidth()/2,GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().y-this.getHeight()/2);
this.t=t;
Font font = new Font("Courier", Font.BOLD,20);
lbl_digi=new JLabel("Digital Clock");
lbl_digi.setBounds(10,10,180,20);
lbl_digi.setFont(new Font("Vardana",Font.BOLD,16));
lbl_digi.setHorizontalAlignment(JLabel.CENTER);
    lbl_digi.setVerticalAlignment(JLabel.CENTER);

timeString=new JLabel();
timeString.setBounds(10,30,180,20);
timeString.setFont(font);
timeString.setHorizontalAlignment(JLabel.CENTER);
    timeString.setVerticalAlignment(JLabel.CENTER);

start=new JButton("Stop");
start.setBounds(10,60,180,30);

start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
try{
if(start.getText().equals("stop")){
start.setText("start");
ClockScreen.this.t=Thread.currentThread();
ClockScreen.this.t.yield();
System.out.println("jiten");
}else{
start.setText("stop");
}
}catch(Exception ex){
System.out.println("Error:"+ex.getMessage());
}
}
}); 
add(timeString);
add(lbl_digi);
add(start);
}
public void setLabelValue(String value){
timeString.setText(value);
}
}
class clock implements Runnable{
int hour,minute,second;
String strTime;
private Thread t;
private ClockScreen c1;
private String threadName;
public clock( String name){
      threadName = name;
      System.out.println("Creating " +  threadName );
c1=new ClockScreen(t);
  }
public void run() {
System.out.println("Running " +  threadName );
try {
int i=Calendar.getInstance().get(Calendar.SECOND);
while(true){
Calendar cal=Calendar.getInstance();

hour=cal.get(Calendar.HOUR_OF_DAY);

if(hour >12)
hour-=12;
minute=cal.get(Calendar.MINUTE);
second=cal.get(Calendar.SECOND);
SimpleDateFormat formatter=new SimpleDateFormat("HH:mm:ss");
Date date=cal.getTime();
strTime=formatter.format(date);
System.out.println(strTime);
System.out.println("Thread: " + threadName + ", " + second+"\t i:"+(i));
c1.setLabelValue(strTime);
/*if((second-i)>=10)
System.exit(0);*/
            Thread.sleep(1000);
        }
} catch (InterruptedException e) {
System.out.println("Thread " +  threadName + " interrupted.");
}
System.out.println("Thread " +  threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " +  threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class DigitalClock{
public static void main(String [] args){
clock c1=new clock("First");
c1.start();
}
}

run this program by following command:

<complilation>$javac DigitalClock.java
<run>$ java DigitalClock

Download Program: Click Here

output:







Monday, 16 May 2016

Reading Data From XML file in JAVA

Reading Data From XML file in JAVA

Reading of xml data from file you need to parse xml it means you need to go through xml 

Program:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class xmlReader {

  public static void main(String argv[]) {

    try {

File fXmlFile = new File("person.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Staff");
System.out.println("----------------------------");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) 
System.out.println("First Name : " + eElement.getElementsByTagName("FirstName").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastName").item(0).getTextContent());
System.out.println("Salary : " + eElement.getElementsByTagName("Salary").item(0).getTextContent());

}
}
    } catch (Exception e) {
e.printStackTrace();
    }
  }

}

To Run Program:
(compilation) $ javac xmlReader.java
(run) $ java xmlReader

Download Program: Click Here

Output:

Writing Data in XML file Using JAVA

Writing Data in XML file Using JAVA

DOM provides many handy classes to create XML file easily. Firstly, you have to create a Document withDocumentBuilder class, define all the XML content – node, attribute with Element class. In last, use Transformer class to output the entire XML content to stream output, typically a File.


Download File: Click Here


Program:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.*;
import java.util.*;



public class xmlDemo{

     public static void main(String []args){
       // System.out.println("Hello World");
       Scanner userinput=new Scanner(System.in);
try{
     
         DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
         DocumentBuilder builder=dbFactory.newDocumentBuilder();
         
         Document doc=builder.newDocument();
         
         Element rootElement=doc.createElement("Person");
         doc.appendChild(rootElement);
         
         for(int i=0;i<5;i++){
        Element staff=doc.createElement("Staff");
        rootElement.appendChild(staff);
        
System.out.print("Enter First Name:");
String fname=userinput.nextLine();

        Element firstName=doc.createElement("FirstName");
        firstName.appendChild(doc.createTextNode(fname));
        staff.appendChild(firstName);
        
        System.out.print("Enter Last Name:");
String lname=userinput.nextLine();
        Element lastName=doc.createElement("lastName");
        lastName.appendChild(doc.createTextNode(lname));
        staff.appendChild(lastName);
        
        
        System.out.print("Enter Salary:");
String usalary=userinput.nextLine();
        Element salary=doc.createElement("Salary");
        salary.appendChild(doc.createTextNode(usalary));
        staff.appendChild(salary);
         }
         TransformerFactory transformerFactory =TransformerFactory.newInstance();
         Transformer transformer =transformerFactory.newTransformer();
//Transformer.setOutputProperty(OutputKeys.INDENT,"yes");
         DOMSource source = new DOMSource(doc);
         StreamResult result =new StreamResult(new FileWriter("person.xml"));
         transformer.transform(source, result);
         System.out.println("Xml File Write Successfully....");
        
       }catch(Exception ex){
            System.out.println("Error: "+ex.getMessage());
           
       }
     }
}


How to Run:

(compilatin) $ javac xmlDemo.java
(run) $ java xmlDemo

output:



Wednesday, 2 March 2016

Dynamic Textbox adding with summation in javascript

Dynamic Textbox adding with summation in javascript


requirement:
1. add new textbox when click on + button
before click
after click
2. Remove textbox when click on - button
before click:

after click:
3. count sum of each textbox available on screen if the value in the text box is string or blank then ignore it.


Download Script: click here

Script:
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <div id="space" >
      <!--division for main textbox and button-->
    <input type="text" id="mainTextBox">
    <button type="button" onclick="addTextBox()" id="btn1"><b>+</b></button>
    </div>
    <div id="myDiv">
      <!--space for dynamic control insertion-->
    </div>
    <div id="total">
      <hr/>
      <input type="text" id="txt_Total_Value"/>
      <input type="button" onclick="countTotal()" value="="/>
    </div>
    
   
    <script>
    var id_bucket=new Array();
     var total_element=0;
    //create new division with textbox and button inside it
      function addTextBox(){
        var div=document.createElement('DIV');
        total_element++;
        //insert id into id b
        id_bucket[total_element]=total_element;
          div.innerHTML=dynamicTextBox(total_element);
        document.getElementById("myDiv").appendChild(div);
      }
      //create textbox and button and return to the caller function
      function dynamicTextBox(value){
        return '<input type="text" name="atrib[]" id="'+value+'" value=""/>'+
        '<input type="button" onclick="removeTextBox(this)" value="-" id="'+value+'"/>'
        
      }
    // remove perticulor division from the page
      function removeTextBox(div){
      var count1=document.getElementById("mainTextBox").value;
      var sum=0;
      var j=1;
      id_bucket[parseInt(div.id)]=0;
       if(count1.length <1){
          sum=0;
        }
        else if(isNaN(count1)){
          sum=0;
        }else{ 
          sum=parseFloat(count1);
        }
      for(;j<=total_element;j++){
        if(id_bucket[j]!=0){
         var num=document.getElementById(j).value;
if(num.length<1)
continue;
         if(!isNaN(num)){
           sum+=parseFloat(document.getElementById(j).value);
         }
        }
      }
      document.getElementById("txt_Total_Value").value=sum;
       document.getElementById("myDiv").removeChild(div.parentNode);
      }
      function countTotal(){
       var count1=document.getElementById("mainTextBox").value;
        var j=1;
        var sum=0;
        if(count1.length <1){
          sum=0;
        }
        else if(isNaN(count1)){
          sum=0;
        }else{ 
          sum=parseFloat(count1);
        }
        for(;j<=total_element;j++){
        if(id_bucket[j]!=0){
         var num=document.getElementById(j).value;
if(num.length<1)
continue;
         if(!isNaN(num)){
           sum+=parseFloat(document.getElementById(j).value);
         }
        }
        }
       document.getElementById("txt_Total_Value").value=sum;
      }
    </script>
  </body>

</html>

Monday, 2 November 2015

Reverse an Order Of a String Using JAVA

Reverse an Order Of a String Using JAVA

In this post i am going to show you how to reverse the order of the given string. the order of the string will be reverse means the last whole word become the first and first become the last word of the string and other remaining word also change the position in the order they appear.

Example: jiten vaghela
ouput: vaghela jiten

Download Program: Click here

Program:

import java.util.*;

public class reverseOrder{
public static void main(String [] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter your String:");
String data=input.nextLine();
String [] arrayData=data.split(" ");

data=new String("");
for(int i=arrayData.length-1;i>=0;i--){
data+=arrayData[i]+" ";
}
System.out.println("Reverse String:"+data);
}
}

output:


Count Sub String Occurrence Algorithm With Example using JAVA

Count Sub String Occurrence Algorithm With Example using JAVA

Sub String Occurrence count means to check how many  times a particular  part of a string repeat in the given string.

Algorithm:

step 1: get the length of MainString and SubString variables and initialize i=j=count=0;
            ex:
            len1=mainString.length();
            len2=subString.length();

Step 2: start loop from i=0 to len1-len2;
            initialize the j with 0 and flag with true;

Step 3: check whether character of mainString at position i is equals to character of SubString at position j ?
             ex:
             if(mainString.charAt(i)==subString.charAt(j))

Step 4: if both are sem then start another loop with j=1 and j is j<=subString.length(); now check whether the character of mainString at position i+j is not Equals to character of SubString at position j. then make the flag = false and break the loop.
           ex:
           for(j=1;j<=SubString.length();j++){
                         if(mainString.charAt(i+j)!=subString(j)){
                                     flag=false;
                                       break;
                          }
            }

Step 5:out side the inner for loop check whether the flag value is true if yes then count= count+1
            ex:
            if(flag)
               count++;

Download Program: Click Here

Program:

import java.util.*;

public class reverse{
public static int getSubString(String mainString,String subString){
int max=1+mainString.length()-subString.length();
int count=0;
for(int i=0;i<max;i++){
boolean flag=true;
int j=0;
if(mainString.charAt(i)==subString.charAt(j)){
for(j=1;j<subString.length();j++){
if(mainString.charAt(i+j)!=subString.charAt(j)){
flag=false;
break;
}
}

}else
flag=false;
if(flag)
count++;
}
return count;
}
public static void main(String [] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter Main String:");
String mainString=input.nextLine();
System.out.print("Enter Sub String :");
String subString=input.nextLine();

int count=getSubString(mainString,subString);

System.out.println("String Found:"+count);
}
}

compile the above code:javac subStringcounter.java
To Run the code: java subStringcounter

Output:


Tuesday, 27 October 2015

Fibonacci Series Using JAVA

Fibonacci Series Using JAVA


More Details About Fibonacci Series: Click Here

Program in JAVA

public class fibo{
public static void main(String args[]){
int no=10;
int next,prev,sum;
next=1;
prev=0;
for(int i=0;i<no;i++){
System.out.print(prev+"  ");
sum=next+prev;
prev=next;
next=sum;
}
}
}

Download Program File: Click Here

Output:


Pascal's Triangle Using JAVA

Pascal's Triangle Using JAVA


In mathematics, Pascal's triangle is a triangular array of the binomial coefficients. In much of the Western world it is named after French mathematician Blaise Pascal, although other mathematicians studied it centuries before him in India, Iran, China, Germany, and Italy.
The rows of Pascal's triangle (sequence A007318 in OEIS) are conventionally enumerated starting with row n = 0 at the top (the 0th row). The entries in each row are numbered from the left beginning with k = 0 and are usually staggered relative to the numbers in the adjacent rows. Having the indices of both rows and columns start at zero makes it possible to state that the binomial coefficient \tbinom{n}{k} appears in the nth row and kth column of Pascal's triangle. A simple construction of the triangle proceeds in the following manner: In row 0, the topmost row, the entry is \tbinom{0}{0} = 1 (the entry is in the zeroth row and zeroth column). Then, to construct the elements of the following rows, add the number above and to the left with the number above and to the right of a given position to find the new value to place in that position. If either the number to the right or left is not present, substitute a zero in its place. For example, the initial number in the first (or any other) row is 1 (the sum of 0 and 1), whereas the numbers 1 and 3 in the third row are added to produce the number 4 in the fourth row.
This construction is related to the binomial coefficients by Pascal's rule, which says that if
(x+y)^n=\sum_{k=0}^n{n \choose k}x^{n-k}y^{k}
then
 {n \choose k} = {n-1 \choose k-1} + {n-1 \choose k}
for any non-negative integer n and any integer k between 0 and n.
Pascal's triangle has higher dimensional generalizations. The three-dimensional version is called Pascal's pyramid or Pascal's tetrahedron, while the general versions are called Pascal's simplices.

Program Using JAVA:

public class pascal{
public static void main(String args[]){
int row=10;

for(int i=0;i<row;i++){
int no=1;
System.out.format("%"+(row-i)*2+"s","");
for(int j=0;j<=i;j++){
System.out.format("%4d",no);
no=no*(i-j)/(j+1);
}
System.out.println();
}
}
}

Download Program File: Click Here

Output:


Tower Of Hanoi with Recursion Using JAVA

Tower Of Hanoi with Recursion Using JAVA


The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower, and sometimes pluralized) is a mathematical game or puzzle.It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
  1. Only one disk can be moved at a time.
  2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  3. No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks.

More Details About Tower Of Hanoi: Click Here

Program Using JAVA:

import java.util.*;

public class HanoiTower{

public static void doTower(int disk,char from,char mid,char end){
if(disk==1){
System.out.println("Disk 1 from "+from+" To "+end);
}else{
doTower(disk-1,from,end,mid);
System.out.println("Disk "+disk+" From "+from+" To "+end);
doTower(disk-1,mid,from,end);
}
}
public static void main(String args[]){
Scanner input=new Scanner(System.in);
int disk;
System.out.print("Enter No Of Disk:");
disk=Integer.parseInt(input.nextLine());
if(disk<=0){
System.out.println("Invalid Disk SIze");
}else{
doTower(disk,'A','B','C');
}
}
}

Download Program File: Click Here

output:




Tower of Hanoi without recursion using java

Tower of Hanoi without recursion using java



Program Using JAVA:

import java.util.*;

public class TowerOfHanoi{
public static int makeTower(Stack A,Stack B){
int a,b;
try{
a=Integer.parseInt(A.peek().toString());
}catch(Exception e){
a=0;
}
try{
b=Integer.parseInt(B.peek().toString());
}catch(Exception e){
b=0;
}
if(a==b) return 0;
if(a==0){
A.push(B.pop());
return 2;
}
else if(b==0){
B.push(A.pop());
return 1;
}
if(a>b){
A.push(B.pop());
return 2;
}
else if(a<b){
B.push(A.pop());
return 1;
}
return -1;
}
public static void main(String args[]){
Scanner input = new Scanner(System.in);
try{
Stack source=new Stack();
Stack Auxilary=new Stack();
Stack Destination=new Stack();
int stepno=0;
int status=0;

System.out.print("Enter no Of Disk:");
int disk=Integer.parseInt(input.nextLine());

if(disk<=0){
System.out.println("Invalid Disk Size");
System.exit(1);
}
for(int i=disk;i>0;i--)
source.push(i);
int m=disk%2;
do{
if(m==1){
status=makeTower(source,Destination);
if(status==1){
System.out.println((++stepno)+"Source --> Destination");
}
else if(status==2){
System.out.println((++stepno)+"Destination --> Source");
}
status=makeTower(source,Auxilary);
if(status==1){
System.out.println((++stepno)+"Source -->Auxilary");
}
else if(status==2){
System.out.println((++stepno)+"Auxilary --> Source");
}else
break;
}else{
status=makeTower(source,Auxilary);
if(status==1){
System.out.println((++stepno)+"Source -->Auxilary");
}
else if(status==2){
System.out.println((++stepno)+"Auxilary --> Source");
}
status=makeTower(source,Destination);
if(status==1){
System.out.println((++stepno)+"Source --> Destination");
}
else if(status==2){
System.out.println((++stepno)+"Destination --> Source");
}
}
status=makeTower(Auxilary,Destination);
if(status==1){
System.out.println((++stepno)+"Auxilary --> Destination");
}
else if(status==2){
System.out.println((++stepno)+"Destination --> Auxilary");
}

}while(Destination.size()!=disk);
System.out.println("\nfinish");
}catch(Exception ex){}
}
}

download program file: click here

output:


Sunday, 17 May 2015

Fibonacci number using C language

Fibonacci number using C language

The Fibonacci sequence is named after Italian mathematician Fibonacci His 1202 book Liber Abaci introduced the sequence to Western European mathematics, although the sequence had been described earlier in Indian mathematics. By modern convention, the sequence begins either with F0 = 0 or with F1 = 1. The Liber Abaci began the sequence with F1 = 1.
Fibonacci numbers are closely related to Lucas numbers in that they are a complementary pair of Lucas sequences. They are intimately connected with the golden ratio; for example, the closest rational approximations to the ratio are 2/1, 3/2, 5/3, 8/5, ... . Applications include computer algorithms such as the Fibonacci search technique and the Fibonacci heap data structure, and graphs called Fibonacci cubes used for interconnecting parallel and distributed systems. They also appear in biological settings such as branching in trees, phyllotaxis (the arrangement of leaves on a stem), the fruit sprouts of a pineapple the flowering of an artichoke, an uncurling fern and the arrangement of a pine cone's bracts.

for more detail: click here 


program:
#include <stdio.h>

// Fibonacci Series
/*
   Fibo(0)=1
   Fibo(1)=1
   Fibo(n) = Fibo(n-1)+Fibo(n-2)
*/

int Fibo(int no)
{
  int no1, no2;

  if (no==0)
    return 1;
  else
  if (no==1)
    return 1;
  else
  {
    no1 = Fibo(no-1);
    no2 = Fibo(no-2);
    return (no1+no2);
  }
}

void main()
{
  int i, number;

  clrscr();

  printf("Enter an integer : ");
    scanf("%d", &number);
  fflush(stdin);

  printf("Fibo(%d) = %d\n\n", number, Fibo(number));

  for (i=0; i<=number; i++)
    printf("Fibo(%d)\t= %10d\n", i, Fibo(i));

  getch();
}


Saturday, 16 May 2015

greatest common divisor (gcd) using C language

greatest common divisor (gcd) using C Language

the Greatest Common Divisor (GCD) of two whole numbers, also called the Greatest Common Factor (GCF) and the Highest Common Factor (HCF), is the largest whole number that's a divisor (factor) of both of them. For instance, the largest number that divides into both 20 and 16 is 4. (Both 16 and 20 have larger factors, but no larger common factors -- for instance, 8 is a factor of 16, but it's not a factor of 20.) In grade school, most people are taught a "guess-and-check" method of finding the GCD. Instead, there is a simple and systematic way of doing this that always leads to the correct answer. The method is called "Euclid's algorithm." If you want to know how to truly find the Greatest Common Divisor of two integers.



for more Details: click here

program:
# include <stdio.h>

/* Definition of the Greatest Comman Divisor Function */
int GCD(int n, int m)
{
  if ((n>=m) && ((n%m)==0))
    return(m);
  else
    return GCD(m,(n%m));
}

/* main function */
void main()
{
  int no1, no2;
  int GCDresult;

  clrscr();
  printf("Program for GCD caluclation\n\n");

  printf("Input 2 integer numbers: ");
    scanf("%d%d", &no1,&no2);
  printf("\n\n");

  GCDresult = GCD(no1, no2);
  printf("no1 = %d\n", no1);
  printf("no2 = %d\n\n", no2);

  printf("Greatest Comman Diviser = %d\n", GCDresult);
  getch();
}

tower of hanoi using c language

Tower of Hanoi using c language

Tower of Hanoi

The Tower of Hanoi puzzle was invented by the French mathematician Edouard Lucas in 1883. He was inspired by a legend that tells of a Hindu temple where the puzzle was presented to young priests. At the beginning of time, the priests were given three poles and a stack of 64 gold disks, each disk a little smaller than the one beneath it. Their assignment was to transfer all 64 disks from one of the three poles to another, with two important constraints. They could only move one disk at a time, and they could never place a larger disk on top of a smaller one. The priests worked very efficiently, day and night, moving one disk every second. When they finished their work, the legend said, the temple would crumble into dust and the world would vanish.
Although the legend is interesting, you need not worry about the world ending any time soon. The number of moves required to correctly move a tower of 64 disks is 264−1=18,446,744,073,709,551,615. At a rate of one move per second, that is 584,942,417,355 years! Clearly there is more to this puzzle than meets the eye.
Figure 1 shows an example of a configuration of disks in the middle of a move from the first peg to the third. Notice that, as the rules specify, the disks on each peg are stacked so that smaller disks are always on top of the larger disks. If you have not tried to solve this puzzle before, you should try it now. You do not need fancy disks and poles–a pile of books or pieces of paper will work.
image
Figure 1: An Example Arrangement of Disks for the Tower of Hanoi
How do we go about solving this problem recursively? How would you go about solving this problem at all? What is our base case? Let’s think about this problem from the bottom up. Suppose you have a tower of five disks, originally on peg one. If you already knew how to move a tower of four disks to peg two, you could then easily move the bottom disk to peg three, and then move the tower of four from peg two to peg three. But what if you do not know how to move a tower of height four? Suppose that you knew how to move a tower of height three to peg three; then it would be easy to move the fourth disk to peg two and move the three from peg three on top of it. But what if you do not know how to move a tower of three? How about moving a tower of two disks to peg two and then moving the third disk to peg three, and then moving the tower of height two on top of it? But what if you still do not know how to do this? Surely you would agree that moving a single disk to peg three is easy enough, trivial you might even say. This sounds like a base case in the making.
Here is a high-level outline of how to move a tower from the starting pole, to the goal pole, using an intermediate pole:
  1. Move a tower of height-1 to an intermediate pole, using the final pole.
  2. Move the remaining disk to the final pole.
  3. Move the tower of height-1 from the intermediate pole to the final pole using the original pole.
As long as we always obey the rule that the larger disks remain on the bottom of the stack, we can use the three steps above recursively, treating any larger disks as though they were not even there. The only thing missing from the outline above is the identification of a base case. The simplest Tower of Hanoi problem is a tower of one disk. In this case, we need move only a single disk to its final destination. A tower of one disk will be our base case. In addition, the steps outlined above move us toward the base case by reducing the height of the tower in steps 1 and 3


 for more detail: click hera
program:
 # include <stdio.h>

/* Definition of the Tower Of Hanoi generator function */
void TowerOfHanoi(char peg1, char peg2, char  peg3, int no)
{
  if (no==1)
    printf("   Move Disk from %c ==> %c\n", peg1, peg3);
  else
  {
    TowerOfHanoi(peg1, peg3, peg2, no-1);
    TowerOfHanoi(peg1, peg2, peg3, 1);
    TowerOfHanoi(peg2, peg1, peg3, no-1);
  }
}

/* main function */
int main()
{
  int noDisks;

//  clrscr();
  printf("Solving Tower of Hanoi puzzle\n\n");
  printf("Input the number of disc: ");
    scanf("%d", &noDisks);
  if (noDisks<=0)
    printf("No of disks = %d is an INVALID value\n", noDisks);
  else
  {
    printf("Moving %d disks from peg A to peg C\n\n");
    TowerOfHanoi('A', 'B', 'C', noDisks);
  }

//  getch();
}