Interview Java Programs


Floyds Triangle

import java.io.*;
class FloydsTriangle
{
public static void main(String args[]) throws Exception
{
int num,i,j,k,s=40;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter number “);
num=Integer.parseInt(br.readLine());
for(i=1;i<=num;i++)
{
for(j=1;j<=s;j++)
System.out.print(” “);
for(k=1;k<=i;k++)
System.out.print(k);
for(k=i-1;k>0;k–)
System.out.print(k);
System.out.print(“\n”);
s–;
}
}
}

Output is:

Enter number
5
1
121
12321
1234321
123454321

 

//Reversing of String program 1
class ReversingStr1
{
public static void main(String args[])
{
String st=args[0];
String reversed=ReversingStr1.reverseMe(st);
System.out.println(“”+reversed);

}
static String reverseMe(String re)
{
StringBuilder sb=new StringBuilder();
for(int i=re.length()-1; i>=0;–i)
{
sb.append(re.charAt(i));
}
return sb.toString();
}
}

//Reversing of String program 2

class RevesingStr2
{
public static void main(String args[])
{
String st=args[0];
String reversed=RevesingStr2.reverseMe(st);
System.out.println(“”+reversed);
}
public static String reverseMe(String s)
{
if(s.length()==0)
return “”;
return s.charAt(s.length()-1)+reverseMe(s.substring(0, s.length()-1));
}

Tower of Hanoi

import java.io.*;
class TowerOfHanoi
{
public static void main(String args[])throws IOException
{
hanoi obj=new hanoi();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter number of rings”);
int N=Integer.parseInt(br.readLine());
obj.ha(‘A’,’B’,’C’,N);
}
}

class hanoi
{
void ha(char a,char b,char c,int n)
{
if(n==0)
System.out.println(“WRONG INPUT !!!”);
if(n==1)
System.out.println(“Move from “+a+” to “+c);
if(n>1)
{
ha(a,c,b,n-1);
ha(a,b,c,1);
ha(b,a,c,n-1);
}
}
}

Output

Enter number of rings
3
Move from A to C
Move from A to B
Move from C to B
Move from A to C
Move from B to A
Move from B to C
Move from A to C

 
}

 

About pacesettergraam

A good and realistic person

Posted on February 15, 2013, in Java and tagged . Bookmark the permalink. 1 Comment.

  1. why not String s0 = args[0];
    StringBuffer s01 = new StringBuffer(s0);
    System.out.println(s01.reverse());

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: