Saturday, July 1, 2017

Write a program to find common elements between two arrays.


Description:
Write a program to identify common elements or numbers between
two given arrays. You should not use any inbuilt methods are list to
find common values.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.govindsblog.algos;
 
public class CommonElementsInArray {
 
    public static void main(String a[]){
        int[] arr1 = {4,7,3,9,2};
        int[] arr2 = {3,2,12,9,40,32,4};
        for(int i=0;i<arr1.length;i++){
            for(int j=0;j<arr2.length;j++){
                if(arr1[i]==arr2[j]){
                    System.out.println(arr1[i]);
                }
            }
        }
    }
}

Output:
4
3
9
2

Friday, June 30, 2017

How to swap two numbers without using temporary variable?


Description:
Write a program to swap or exchange two numbers. You should
not use any temporary or third variable to swap.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.govindsblog.algos;
 
public class MySwapingTwoNumbers {
 
    public static void main(String a[]){
        int x = 10;
        int y = 20;
        System.out.println("Before swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);
        x = x+y;
        y=x-y;
        x=x-y;
        System.out.println("After swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);
    }
}

Output:
Before swap:
x value: 10
y value: 20
After swap:
x value: 20
y value: 10