Showing posts with label Java Program. Show all posts
Showing posts with label Java Program. Show all posts

Wednesday, 13 June 2018

Reverse String using recursion in Java



Sample Program:-


 public class SampleProgram {  
      public static void main(String[] args) {  
           String str = "abcde";  
           reverseStringRecurively(str);  
      }  
      private static void reverseStringRecurively(String str) {  
           if (str.length() == 1) {  
                System.out.print(str);  
           } else {  
                reverseStringRecurively(str.substring(1, str.length()));  
                System.out.print(str.substring(0, 1));  
           }  
      }  
 }  

Output:-


 edcba  

Enjoy Coding

Monday, 11 June 2018

Fibonacci series using recursion in java


Sample Program:-


 public class SampleProgram {  
      public static void main(String[] args) {  
           int n = 5;  
           System.out.print("Fibonacci Series: 0 1 ");  
           for (int i = 2; i <= n; i++) {  
                System.out.print(fibonacciRecursion(i) + " ");  
           }  
      }  
      private static int fibonacciRecursion(int n) {  
           if (n == 1 || n == 2) {  
                return 1;  
           }  
           return fibonacciRecursion(n - 1) + fibonacciRecursion(n - 2);  
      }  
 }  

Output:-


 Fibonacci Series: 0 1 1 2 3 5   

Enjoy Coding.

Sum of digits in number using recursion in java



Sample Program:-


public class SampleProgram {  
      static int sum = 0;  
      public static void main(String[] args) {  
           int number = 1234;  
           System.out.println("sum of digits : " + sumOfDigits(number));  
      }  
      private static int sumOfDigits(int number) {  
           if (number == 0) {  
                return sum;  
           } else {  
                sum = sum + (number % 10);  
                sumOfDigits(number / 10);  
           }  
           return sum;  
      }  
 }  

Output:-


 sum of digits : 10  

Enjoy Coding.

Merge two sorted arrays in Java


Suppose we have 2 sorted arrays a1={1,3,5,7} and a2={2,4,6}.We have to merge this 2 arrays to generate below result

a3={1,2,3,4,5,6,7}


Sample Program:-


public class MergeSortedArray {  
      public static void main(String[] args) {  
           int[] ar1 = { 1, 3, 5, 7 };  
           int[] ar2 = { 2, 4, 6, 8 };  
           int mergedArray[] = merge(ar1, ar2);  
           System.out.print("\nMerged array: ");  
           for (int i = 0; i < mergedArray.length; i++)  
                System.out.print(mergedArray[i] + " ");  
      }  
      private static int[] merge(int[] ar1, int[] ar2) {  
           int mergedArray[] = new int[ar1.length + ar2.length];  
           int ar1Index = 0, ar2Index = 0, mergedArrayIndex = 0;  
           while (ar1Index < ar1.length && ar2Index < ar2.length)  
                if (ar1[ar1Index] < ar2[ar2Index])  
                     mergedArray[mergedArrayIndex++] = ar1[ar1Index++];  
                else  
                     mergedArray[mergedArrayIndex++] = ar2[ar2Index++];  
           while (ar1Index < ar1.length)  
                mergedArray[mergedArrayIndex++] = ar1[ar1Index++];  
           while (ar2Index < ar2.length)  
                mergedArray[mergedArrayIndex++] = ar2[ar2Index++];  
           return mergedArray;  
      }  
 }  

Output:-


 Merged array: 1 2 3 4 5 6 7 8   

Enjoy Coding.

Tuesday, 29 May 2018

Java Program to find number of times sorted array has been rotated



Sample Program:-


public class SampleProgram {  
      public static void main(String[] args) {  
           int ar[] = { 4, 1, 2, 3 };  
           for (int i = 0; i < ar.length; i++) {  
                if (i + 1 == ar.length) {  
                     System.out.println("Array is not rotated");  
                } else {  
                     if (ar[i] > ar[i + 1]) {  
                          System.out.println("Array has been rotated by " + (i + 1) + " position");  
                          break;  
                     }  
                }  
           }  
      }  
 }  


Output:-


Array has been rotated by 1 position  

Enjoy Coding.

Java Program to sort Binary Array



Sample Program:-


public class SampleProgram {  
      public static void main(String[] args) {  
           int ar[] = { 1, 0, 1, 1, 0, 1, 0, 1 };  
           System.out.print("Before sorting : ");  
           for (int n : ar)  
                System.out.print(n);  
           int i = 0, j = ar.length - 1;  
           while (i < j) {  
                if (ar[i] > ar[j]) {  
                     ar[i] = 0;  
                     ar[j] = 1;  
                     i++;  
                     j--;  
                }  
                else if (ar[i] == 0 && ar[j] == 0) {  
                     i++;  
                }  
                else if (ar[i] == 1 && ar[j] == 1) {  
                     j--;  
                }  
                else if (ar[i] < ar[j]) {  
                     i++;  
                     j--;  
                }  
           }  
           System.out.print("\nAfter sorting : ");  
           for (int n : ar)  
                System.out.print(n);  
      }  
 }  


Output:-


Before sorting : 10110101  
 After sorting : 00011111  

Enjoy Coding.

Java program to change case in String



Sample Program:-


 public class SampleProgram {  
      public static void main(String[] args) {  
           String s = "inSeRt";  
           char ar[] = s.toCharArray();  
           for (int i = 0; i < ar.length; i++) {  
                if (ar[i] >= 65 && ar[i] <= 90) { // convert upperCase to lowerCase  
                     ar[i] += 32;  
                } else if (ar[i] >= 97 && ar[i] <= 122) { // convert lowerCase to  
                                                                       // upperCase.  
                     ar[i] -= 32;  
                }  
           }  
           System.out.println(new String(ar));  
      }  
 }  

Output:-


INsErT  

Enjoy Coding.

Java Program to find all duplicate elements in List



Sample Program:-


 import java.util.ArrayList;  
 import java.util.List;  
 public class SampleProgram {  
      public static void main(String[] args) {  
           List<Integer> list = new ArrayList<Integer>();  
           list.add(1);  
           list.add(2);  
           list.add(5);  
           list.add(3);  
           list.add(3);  
           list.add(1);  
           list.add(7);  
           System.out.println("Original list: " + list);  
           List<Integer> newList = new ArrayList<Integer>();  
           System.out.print("Duplicate numbers in list are: ");  
           for (int i : list) {  
                if (newList.contains(i))  
                     System.out.print(i + " ");  
                else  
                     newList.add(i);  
           }  
      }  
 }  

Output:-


 Original list: [1, 2, 5, 3, 3, 1, 7]  
 Duplicate numbers in list are: 3 1   

Enjoy Coding.

Find index in an array such that sum of left elements is equal to sum of right in Java



Sample Program:-


 public class SampleProgram {  
      public static void main(String[] args) {  
           int ar[] = { 2, 4, 4, 1, 1 };  
           int leftIndex = 0, rightIndex = ar.length - 1;  
           int leftSum = 0, rightSum = 0;  
           while (leftIndex <= rightIndex) {  
                if (leftSum > rightSum)  
                     rightSum = rightSum + ar[rightIndex--];  
                else  
                     leftSum = leftSum + ar[leftIndex++];  
           }  
           if (leftSum == rightSum)  
                System.out.println("Index is:" + (rightIndex + 1));  
           else  
                System.out.println("index Not Found");  
      }  
 }  

Output:-


Index is:2  

Enjoy Coding.

Java Program to find largest of Three Numbers



Sample Program:-


 public class LargestNumber {  
      public static void main(String[] args) {  
           int a, b, c;  
           a = 20;  
           b = 30;  
           c = 40;  
           if (a > b && a > c)  
                System.out.println("a is largest");  
           else if (a < b && b > c)  
                System.out.println("b is largest");  
           else if (a < c && b < c)  
                System.out.println("c is largest");  
           else  
                System.out.println("a, b, c are not different");  
      }  
 }  


Output:-


 c is largest  


Enjoy Coding.

Java Program to convert Decimal into Binary



Sample Program:-


 public class DecimalToBinary {  
      public static void main(String[] args) {  
           int decimal = 14;  
           if (decimal == 0) {  
                System.out.println("0");  
           }  
           String binary = "";  
           while (decimal > 0) {  
                binary = (decimal % 2) + binary;  
                decimal = decimal / 2;  
           }  
           System.out.println("Binary value is:" + binary);  
      }  
 }  

Output:-


Binary value is:1110  

Enjoy Coding.

Java Program to convert binary into decimal



Binary Numbers are represented in the form of 0's and 1's.

For example:-10 is 2 in decimal form

Sample Program:-


public class BinaryToDecimal {  
      public static void main(String[] args) {  
           int binary = 1110;  
           int decimal = 0;  
           int power = 0;  
           while (binary > 0) {  
                decimal += (binary % 10) * Math.pow(2, power++);  
                binary = binary / 10;  
           }  
           System.out.println("Decimal Number is:" + decimal);  
      }  
 }  


Output:-


Decimal Number is:14  

Enjoy Coding.


Find two maximum numbers in array



Sample Program:-


public class MaxtwoNumbers {  
      public static void main(String[] args) {  
           int a[] = { 6, 99, 45, 3, 77 };  
           int max1 = 0;  
           int max2 = 0;  
           for (int i = 0; i < a.length; i++) {  
                if (a[i] > max1) {  
                     max2 = max1;  
                     max1 = a[i];  
                } else if (a[i] > max2) {  
                     max2 = a[i];  
                }  
           }  
           System.out.println("Maximum 2 numbers are:" + max1 + " and " + max2);  
      }  
 }  

Output:-


Maximum 2 numbers are:99 and 77  

Enjoy Coding.

Monday, 28 May 2018

Find sum of all even digits in String




Sample Program:-


public class SumOfAllEven {  
      public static void main(String[] args) {  
           String s = "1j2a3v4a0";  
     char ch[] = s.toCharArray();  
     int sum = 0;  
     for (int i = 0; i < ch.length; i++) {  
         try {  
            int x = Integer.valueOf(String.valueOf(ch[i]));  
            if (x % 2 == 0) {  
               sum += x;  
            }  
         } catch (Exception e) {  
         }  
     }  
     System.out.println(sum);  
      }  
 }  



Output:-


 6  


Explanation:-

Suppose we have String s="java232";
Output for this will be 2+2=4

Enjoy Coding.

Find number is even or odd without using % operator in Java




Sample Program:-


 public class OddOrEven {  
      public static void main(String[] args) {  
           int number = 2;  
           if ((number & 1) == 0)  
                System.out.println("EVEN");  
           else  
                System.out.println("ODD");  
      }  
 }  

Output:-


 EVEN  

Program Logic:-
Binary number consists of only 0's and 1's ,
if last digit is 0, then number is EVEN in java.

if last digit is 1, then number is ODD in java.
For ex:20 is 10100
25 is 11001

Enjoy Coding.

Find Missing numbers between 1 to 100 in sorted array in java



Sample Program:-


 public class MissingNumber {  
      public static void main(String[] args) {  
           int arr[] = { 2, 11, 55, 77, 88, 99 };  
           System.out.println("Given Array: ");  
           for (int j = 0; j < arr.length; j++)  
                System.out.print(arr[j] + " ");  
           System.out.println("\nNumbers missing between 1 to 100 in array:-");  
           int j = 0;  
           for (int i = 1; i <= 100; i++) {  
                if (j < arr.length && i == arr[j])  
                     j++;  
                else  
                     System.out.print(i + " ");  
           }  
      }  
 }  

Output:-


Given Array:
2 11 55 77 88 99
Numbers missing between 1 to 100 in array:-
1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 78 79 80 81 82 83 84 85 86 87 89 90 91 92 93 94 95 96 97 98 100

Enjoy Coding.

Java Program to print Reverse pyramid


Pyramid Sample:-

12345
1234
123
12
1

Sample Program:-


public class ReversePyramid {  
      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  

Enjoy Coding.

Java Program to print Pyramid of stars using nested for loops



Pyramid Example:-

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

Sample Program:-


public class JavaPyramid {  
      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:-


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

Enjoy Programming.

Java Program to Count all distinct pairs with difference equal to k


Given an integer array and a positive integer k, count all distinct pairs with difference equal to k.

Example:-

arr[]:-{1, 5, 3, 4, 2}, k = 3
Output: 2
2 pairs({1, 4} and {5, 2}) with difference equal to 3.

Sample Program:-

package com.shc.ecom.payment.web.rest;  
 /**  
  * @author sdixit  
  *  
  */  
 public class Example {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int arr[] = { 1, 5, 3, 4, 2 };  
           int k = 3;  
           System.out.println("Count of pairs :-" + countPairsWithDiffK(arr, k));  
      }  
      private static int countPairsWithDiffK(int[] arr, int k) {  
           int count = 0;  
           int n = arr.length;  
           for (int i = 0; i < n; i++) {  
                for (int j = i + 1; j < n; j++)  
                     if (arr[i] - arr[j] == k || arr[j] - arr[i] == k)  
                          count++;  
           }  
           return count;  
      }  
 }  


Sample Output:-
 Count of pairs :-2  

Enjoy Programming.

Tuesday, 29 August 2017

Java program to check unique number


Sample Program:-


 import java.util.*;  
 import java.io.*;  
 /**  
  * Created by Dixit on 29-08-2017.  
  */  
 public class IsUniqueNumber {  
   public static boolean  
   isUniqueUsingHash(String word)  
   {char[] chars = word.toCharArray();  
     Set<Character> set = new HashSet<Character>();  
     for (char c : chars)  
       if (set.contains(c))  
         return false;  
       else {  
         set.add(c);  
       }  
     return true;  
   }  
   public static boolean  
   isUniqueUsingSort(String word)  
   {char[] chars = word.toCharArray();  
     if (chars.length <= 1)  
       return true;  
     Arrays.sort(chars);  
     char temp = chars[0];  
     for (int i = 1; i < chars.length; i++)  
     {if (chars[i] == temp)  
       return false;  
       temp = chars[i];  
     }  
     return true;  
   }  
   public static void main(String[] args)  
       throws IOException  
   {  
     System.out.println(isUniqueUsingHash("1234")? "Unique" : "Not Unique");  
         System.out.println(isUniqueUsingSort("123")? "Unique" : "NotUnique");  
   }  
 }  


Enjoy Coding