Pages

Interview Programming


1. Towers of Hanoi Program in Java

public class TowersOfHanoi {
      public void solve(int n, String start, String auxiliary, String end) {
            if (n == 1) {
                  System.out.println(start + " -> " + end);
            } else {
                  solve(n - 1, start, end, auxiliary);
                  System.out.println(start + " -> " + end);
                  solve(n - 1, auxiliary, start, end);
            }
      }
      public static void main(String[] args) {
            TowersOfHanoi towersOfHanoi = new TowersOfHanoi();
            int discs = 2;
            towersOfHanoi.solve(discs, "A", "B", "C");
      }
}

Output :

A -> B     A -> C     B -> C

2. Find LCM and GCD of two Numbers

import java.util.Scanner;
public class GCD_LCM {
        static int gcd(int x, int y) {
            int r=0, a, b;
            a = (x > y) ? x : y; // a is greater number
            b = (x < y) ? x : y; // b is smaller number
            r = b;
            while(a % b != 0) {
                  r = a % b;
                  a = b;
                  b = r;
            }
            return r;
      }
      static int lcm(int x, int y) {
            int a;
            a = (x > y) ? x : y; // a is greater number
            while(true) {
                  if(a % x == 0 && a % y == 0)
                        return a;
                  ++a;
            }
      }
      public static void main(String args[]) {
            int x = 10;
            int y = 20;
            System.out.println("The GCD of two numbers is: " + gcd(x, y));
            System.out.println("The LCM of two numbers is: " + lcm(x, y));
      }
}

Output :

The GCD of two numbers is: 10
The LCM of two numbers is: 20

3. Powerful Number in Java

A Powerful Number is a positive integer m such that for every prime number p dividing m, (p*p) also dives m. Equivalently, a powerful number is the product of a squre and a cube that is a number m of the form m = (a*a)*(b*b*b), where a and b are positive integers. Powerful Numbers are also known as Squareful, Square-full or 2-full.

Powerful Number are : 1,4,8,9,16,25,27,32,36,49,64,72,81,100,108,121,125,128,144,169,196,200,216,225,243,256,288,289, etc.

Program

import java.util.ArrayList;
import java.util.List;
public class PowerfulNumber {
      public static void main(String[] args) {
            System.out.println("powerful Numbers : " + getPowerfulNumbers(1, 40));
      }
      public static List getPowerfulNumbers(int from, int to) {
            List powerfulNums = new ArrayList();
            List primeNumbers = getPrimeNumbers(from, to);
            for (int m = from; m <= to; m++) {
                  boolean isPowerfulNumber = true;
                  for (Integer p : primeNumbers) {
                        // every p that divides m, p*p must also divide m.
                        if(m % p == 0 && m % (p*p) != 0){
                              isPowerfulNumber = false;
                              break;
                        }
                  }
                  if(isPowerfulNumber) {
                        powerfulNums.add(m);
                  }
            }
            return powerfulNums;
      }
      private static List getPrimeNumbers(int from, int to) {
            List primeNumbers = new ArrayList();
            for (int number = from; number <= to; number++) {
                  if(isPrime(number)){
                        primeNumbers.add(number);
                  }
            }
            return primeNumbers;
      }
      private static boolean isPrime(int number) {
            if (number % 2 == 0 || number == 1) {
                  return (number == 2);
            }
            for (int i = 3; i * i <= number; i += 2) {
                  // divisible by other than itself
                  if (number % i == 0){
                        return false;
                  }
            }
            return true;
      }
}

Output :

Powerful Number : 1, 4, 8, 9, 16, 25, 27, 32, 36.

4. Find Largest and Smallest Number in an Array

public class LargestSmallestNumber {
      public static void main(String [ ] args) {
            int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
            int smallest = numbers[0];
            int largetst = numbers[0];
            for(int i=1; i< numbers.length; i++) {
                  if(numbers[i] > largetst)
                        largetst = numbers[i];
                  else if (numbers[i] < smallest)
                        smallest = numbers[i];
            }
            System.out.println("Largest Number is : " + largetst);
            System.out.println("Smallest Number is : " + smallest);
      }
}

Output :

Largest Number is : 98
Smallest Number is : 23

5. Java Static Block Program

public class StaticBlock {
      public static void main(String[] args) {
            System.out.println("Main method is executed.");
      }
      static {
            System.out.println("Static block is executed before main method.");
      }
}

Output :

Static block is executed before main method. Main method is executed.

6. Convert number of days into months and days.

public class ConvertDaysToMonths {
      public static void main(String[] args) {
            int n = 69;
            int d = n%30;
            int m = n/30;
            System.out.println(n +" days = "+ m +" Month and "+ d +" days.");
      }
}

Output :

69 days = 2 Month and 9 days.

7. Generate Harmonic Series

public class HarmonicSeries {
      public static void main(String args[]) {
            int n = 5;
            double result = 0.0;
            while(n > 0) {
                  result = result + (double)1/n;
                  n--;
            }
            System.out.println("Output of Harmonic Series is " + result);
      }
}

Output :

1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately)

8. Identify a given positive decimal number as even/odd without using % or / operator

public class IdentifyEvenOdd {
      public static void main(String arg[]) {
            int num = 6;
            int result = num;
            while(result >= 2) {
                  result = result-2;
            }
            if(result==1) {
                  System.out.println("The number is odd");
            }else{
                  System.out.print("The number is even");
            }
      }
}

Output :

The number is even.

9. Calculate Age based on Date of Birth

public class AgeCalculate {
      int month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
      String id;
      int d = 12, m = 2, y = 1990;
      public void CalculateAge() {
            int date = 0, mon = 0, year = 0;
            if (1 < d && 1 < m) {
                  date = ((month[m - 1] + 01) - d);
                  mon = (12 - m);
                  year = (2012 - y);
           } else if (1 < d && 1 >= m) {
                  date = ((month[m - 1] + 01) - d);
                  mon = (12 - m);
                  year = (2012 - y);
           } else if (d == 1 && 1 < m) {
                  date = 1 - d;
                  mon = (13 - m);
                  year = (2010 - y);
           } else if (d == 1 && m == 1) {
                  date = 1 - d;
                  mon = (13 - m);
                  year = (2012 - y);
           }
           System.out.println(year + " years " + mon + " months " + date + " days");
      }
      public static void main(String [ ] args) {
           AgeCalculate a = new AgeCalculate();
           System.out.println("Your age calculated on 2012/01/01");
           a.CalculateAge();
      }
}

Output :

Your age calculated on 2012/01/01
22 years 10 months 17 days

10. Multiplication or division a number by 2 without using '*' or '/' operator.

public class DivisionAndMultiplication {
      public static void main (String [ ] args) {
            int num = 12;
            int mul = multiplayByTwo (num);
            int div = devideByTwo (num);
            System.out.println ("Result of " + num + "*2 = " + mul);
            System.out.println ("Result of " + num + "/2 = " + dv);
      }
      public static int multiplayByTwo (int num) {
            return (num << 1);
      }       public static int devideByTwo (int num) {
            return (num >> 1);
      }
}

Output :

Result of 12 * 2 = 24.
Result of 12 / 2 = 6.

11. Convert Decimal Number to Binary Number

public class DecimalToBinary {
      public void binaryFormat(int number) {
            int binary[ ] = new int[25];
            int index = 0;
            while(number > 0){
                  binary[index++] = number%2;
                  number = number/2;
            }
            for(int i = index-1;i >= 0;i--){
                  System.out.print("Convert Decimal to Binary :" + binary[i]);
            }
      }
      public static void main(String [ ] args){
            DecimalToBinary dtb = new DecimalToBinary();
            dtb.printBinaryFormat(25);
      }
}

Output :

Convert Decimal to Binary : 11001

12. Convert Decimal Number to Octal Number

public class DecimalToOctal {
      public static void main(String [ ] args) {
            int n = 25;
            int r;
            String s = "";
            char dig[]={'0','1','2','3','4','5','6','7'};
            while(n>0) {
                  r = n%8;
                  s = dig[r] + s;
                  n = n/8;
            }
            System.out.println("Convert Decimal to Octal: " + s);
      }
}

Output :

Convert Decimal to Octal: 31

13. Convert Decimal to Hexadecimal

public class DecimalToHexadecimal {
      public static void main(String args[]) {
            int num = 123;
            int rem;
            String str = "";
            char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
            while(num>0) {
                  rem = num%16;
                  str2 = hex[rem]+str2;
                  num = num/16;
            }
            System.out.println("Convert Decimal to Hexadecimal: " + str);
      }
}

Output :

Convert Decimal to Hexadecimal: 7B

14. Pronic Number or Heteromecic Number or not

Definition : A pronic number, oblong number, rectangular number or heteromecic number, is a number which is the product of two consecutive integers, that is, n (n + 1).Pronic Numbers are: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462 .... etc.
Programming Code:
public class PronicNumber {
      public static void main(String [ ] args) {
            int n = 110;
            int flag = 0;
            for(int i=1; i<=n; i++) {
                  if(i*(i+1) == n) {
                        flag = 1;
                        break;
                  }
            }
            if(flag == 1)
                  System.out.println(n+" is a Pronic Number.");
            } else {
                  System.out.println(n+" is not a Pronic Number.");
            }       }
}

Output:

110 is a Pronic Number.

15. Strong Number

Definition : If sum of factorial of each digit of the number is same as the actual number then that number is called as Strong Number.
Programming Code:
public class StrongNumber {
      public static void main(String [] args) {
            int num=145, i, f, r, sum=0, temp;
            temp=num;
            while(num!=0){
                  i=1;f=1;
                  r=num%10;
                  while(i<=r) {
                        f=f*i;
                        i++;
                  }
                  sum=sum+f;
                  num=num/10;
            }
            if(sum==temp)
                  System.out.println(temp+" is a strong number");
            else
                  System.out.println(temp+" is not a strong number");
            }
      }
}

Output :

145 is a strong number

16. Harshad Number (or) Niven Number

Definition : In recreational mathematics, a Harshad number, is an integer (in base 10) that is divisible by the sum of its digits.
Programming Code:
public class HarshadNumber {
      public static void main(String [ ] args) {
            int n = 195;
            int c = n, d, sum = 0;
            while(c>0) {
                  d = c%10;
                  sum = sum + d;
                  c = c/10;
            }
            if(n%sum == 0)
                  System.out.println(n+" is a Harshad Number.");
            else
                  System.out.println(n+" is not a Harshad Number.");
            }
      }
}

Output :

195 is a Harshad Number

17. Disarium Number

Definition : A number will be called DISARIUM if sum of its digits powered with their respective position is equal to the original number. Disarium Numbers are 89, 175, 518 .... etc.
Programming Code:
public class Disarium {
      public static void main(String [ ] args) {
            int n = 135;
            int copy = n, d = 0, sum = 0;
            String s = Integer.toString(n);
            int len = s.length();
            while(copy>0) {
                  d = copy % 10;
                  sum = sum + (int)Math.pow(d,len);
                  len--;
                  copy = copy / 10;
            }
            if(sum == n)
                  System.out.println(n+" is a Disarium Number.");
            } else {
                  System.out.println(n+" is not a Disarium Number.");
            }
      }
}

Output:

135 is a Disarium Number.

18. Input a word from the user and remove the duplicate characters present in it.

public class RemoveDuplicateCharacter {
      public static void main(String [ ] args) {
            String s = "Mississippi";
            int l = s.length();
            char ch;
            String ans = "";
            for(int i = 0; i < l; i++) {
                  ch = s.charAt(i);
                  if(ch!=' ')
                        ans = ans + ch;
                  s = s.replace(ch,' ');
                  }
            System.out.println("Word after removing duplicate characters : " + ans);
            }
      }
}

Output:

Word after removing duplicate characters : Misp

19. Duck Number

Definition : A Duck number is a number which has zeroes present in it, but there should be no zero present in the beginning of the number. Duck Number are 3210, 7056, 8430709 are all duck numbers whereas 08237, 04309 are not.
Programming Code:
public class DuckNumber {
      public static void main(String [ ] args) {
            String n = 4013;
            int l = n.length();
            int c = 0;
            char ch;
            for(int i = 1; i < l; i++) {
                  ch = n.charAt(i);
                  if(ch=='0')
                        c++;
            }
            char f=n.charAt(0);
            if(c>0 && f!='0') {
                  System.out.println("It is a duck number");
            } else {
                  System.out.println("It is not a duck number");
            }
      }
}

Output:

It is a duck number

20. Automorphic Number with Strings

Definition : An automorphic number is a number which is present in the last digit(s) of its square.
Example: 25 is an automorphic number as its square is 625 and 25 is present as the last digits.
Programming Code:
public class Automorphic {
      public static void main(String [ ] args) {
            int n = 25;
            int sq = n*n;
            String num = Integer.toString(n);
            String square = Integer.toString(sq);
            if(square.endsWith(num))
                  System.out.print(n+" is an Automorphic Number.");
            else
                  System.out.print(n+" is not an Automorphic Number.");
      }
}

Output:

25 is an Automorphic Number.

21. Automorphic Number without using Strings

public class Automorphic {
      public static void main(String [ ] args) {
      int n = 25;
      int sq = n*n;
      int c = 0, copy = n;
      while(copy > 0) {
            c++;
            copy = copy/10;
      }
      int end = sq % (int)Math.pow(10,c);
      if(n == end) {
            System.out.print(n+" is an Automorphic Number.");
      } else {
            System.out.print(n+" is not an Automorphic Number.");
      }
}

Output:

25 is an Automorphic Number.

22. Quadratic Equation Program

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Quadratic {
      public static void main(String args[]) throws NumberFormatException, IOException {
            double x1, x2, disc, a, b, c;
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the a, b, c values : ");
            a = Double.parseDouble(br.readLine());
            b = Double.parseDouble(br.readLine());
            c = Double.parseDouble(br.readLine());
            disc = (b * b) - (4 * a * c);
            if (disc == 0) {
                  System.out.println("Roots are real and equal.");
                  x1 = x2 = -b / 2 * a;
                  System.out.println("Roots are " + x1 + "," + x2);
            } else if (disc > 0) {
                  System.out.println("Roots are real and unequal.");
                  x1 = (-b + Math.sqrt(disc)) / (2 * a);
                  x2 = (-b + Math.sqrt(disc)) / (2 * a);
                  System.out.println("roots are " + x1 + "," + x2);
            } else {
                  System.out.println("Roots are imaginary.");
            }
      }
}

Output:

Enter the a, b, c values : 1 2 3
Roots are imaginary.

23. Print Pyramid First Java Example

public class PyramidFirst {
      public static void main(String[] args) {
            for(int i=5; i>0 ;i--){
                  for(int j=0; j < i; j++){
                        System.out.print(j+1);
                  }
                  System.out.println("");
            }
      }
}

Output :

12345
1234
123
12
1

24. Print Pyramid Second Java Example

public class PyramidSecond {
      public static void main(String[] args) {
            for(int i=1; i<= 5 ;i++){
                  for(int j=0; j < i; j++){
                        System.out.print(j+1);
                  }
                  System.out.println("");
            }
      }
}

Output :

1
12
123
1234
12345

25. Print Pyramid Third Java Example

public class PyramidThird {
      public static void main(String[] args) {
            for(int i=1; i<= 5 ;i++){
                  for(int j=0; j < i; j++){
                        System.out.print("*");
                  }
                  System.out.println("");
            }
      }
}

Output :

*
**
***
****
*****

26. Print Pyramid Fourth Java Example

public class PyramidThird {
      public static void main(String[] args) {
            for(int i=5; i>0 ;i--){
                  for(int j=0; j < i; j++){
                        System.out.print("*");
                  }
                  System.out.println("");
            }
      }
}

Output :

*****
****
***
**
*

27. Print Pyramid Fifth Java Example

public class PyramidFifth {
      public static void main(String[] args) {
            for(int i=1; i<= 5 ;i++){
                  for(int j=0; j < i; j++){
                        System.out.print("*");
                  }
                  System.out.println("");
            }
            for(int i=5; i>0 ;i--){
                  for(int j=0; j < i; j++){
                        System.out.print("*");
                  }
                  System.out.println("");
            }
      }
}

Output :

*
**
***
****
*****
*****
****
***
**
*

28. Generate Pyramid For a Given Number Example

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class GeneratePyramid {
      public static void main (String[] args) throws Exception {
            BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in));
            System.out.println("Enter Number:");
            int as= Integer.parseInt (keyboard.readLine());
            System.out.println("Enter X:");
            int x= Integer.parseInt (keyboard.readLine());
            int y = 0;
            for(int i=0; i<= as ;i++){
                  for(int j=1; j <= i ; j++){
                        System.out.print(y + "\t");
                        y = y + x;
                  }
                  System.out.println("");
            }
      }
}

Output :

Enter the Number: 5
Enter the X: 1
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14

29. A number is given as input. Find the odd digits in the number, add them and find if the sum is odd or not.if even return -1, if odd return 1.

Input : 52315
Logic : 5 + 3 + 1 + 5 = 14(even)
Output : -1

Input : 1112
Logic : 1 + 1 + 1 = 3(odd)
Output : 1

package com.jaladhi;
public class First {
      public static int SumOfOddsAndEvens(int n){
            int n1,n2 = 0,n3;
            while(n != 0) {
                  n1 = n%10;
                  if((n1%2) != 0)
                        n2 += n1;
                  n /= 10;
            }
            if(n2%2 == 0) {
                  n3=-1;
            } else {
                  n3=1;
            }
            return n3;
      }
      public static void main(String[] args) {
            int n = 12346;
            System.out.println(SumOfOddsAndEvens(n));
      }
}

Output :

-1

30.Find the day(Friday) of a date input given as MM-dd-yyyy (format)

Input:12-27-2012
Output:Thursday

package com.jaladhi;
import java.util.*;
import java.text.*;
public class Second {
      public static String getDay(Date d1){
            String s1;
            SimpleDateFormat sdf = new SimpleDateFormat("EEEEE");
            s1 = sdf.format(d1);
            return s1;
      }
      public static void main(String[] args) {
            Date d1 = new Date(2012/12/27);
            System.out.println("day is:"+getDay(d1));
      }
}

Output :

day is : Thursday