how do I use nested-loops to print elements of an array that when added together form the sum of the same array?

229 Views Asked by At

This the test method that I'm using to check if my method works correctly. I know that I must use nested loops but not sure about the implementation of them.

public static void main(String[] args) {
        // Task 1
        int[] array1 = {4, 5, 7, 5, 5, -10};
        System.out.print("Task 1: [");

        // should print [ 4, 5, 7 ]
        for (Integer i : subarray(array1)) {
            System.out.print(" ");
            System.out.print(i);
        }

        System.out.println(" ]");
        
        // should print [ 2 1 1 ]
        int[] array2 = {-6, 2, 1, 1, 5, 3, -2};
        System.out.print("Task 1: [ ");

        for (Integer i : subarray(array2)) {
            System.out.print(" ");
            System.out.print(i);
        }

This the method I have written up so far.

public static int[] subarray(int[] original) {
    int result = 0;
    for(int i = 0; i < original.length; i++) {
        result+=original[i];
    }
    return original;
}
0

There are 0 best solutions below