An array of 10 Elements with some number are missing, How will you find the missing numbers?


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MissingElementsNoLoop {

    public static void main(String[] args) {

        Integer[] numberArray1 = new Integer[10];
        for (int i = 0; i < numberArray1.length; i++) {
            numberArray1[i] = i + 1;
        }
        Integer[] numberArray2 = {1, 2, 4, 5, 7, 8, 9};
        List list1 = new ArrayList(Arrays.asList(numberArray1));
        System.out.println("All Elements List::" + list1);
        List list2 = new ArrayList(Arrays.asList(numberArray2));
        System.out.println("Input Elements List::" + list2);
        list1.removeAll(list2);
        System.out.println("Missed Elements List::" + list1);
    }

}

Advertisements

Calculate the sum of an array without using loops

public class SumNoLoop {

    public static void main(String[] args) {

        int[] array = new int[]{1, 2, 3, 4, 5};
        System.out.println(sum(array, 0));
    }

    public static int sum(int[] arr, int index) {
        if (arr.length <= index) {
            return 0;
        }
        return arr[index] + sum(arr, index + 1);

    }
}

Print a string for n number of times without using loop

public class PrintNTimeNoLoop {

    /**
     * The main method.
     *
     * @param args the arguments
     */
    public static void main(String[] args) {

        int n = 10;
        String input = "String";
        System.out.println(print(n, input));
    }

    /**
     * Prints the character.
     *
     * @param n the n
     * @return the char
     */
    public static String print(int n, String input) {
        if (n == 0)
            return "";
        else {
            return input + "\n"+ print(n - 1, input);
        }
    }

}