user15794248
user15794248

Reputation:

Why the elements in the array are always zero?

I have to code a method called productOfPrevious that takes an array of integers and returns an array of integers of the same size as the input. Each cell in the returned array is the product of the cell by all the previous cells.

    void l3() {
            int[] arr = {1,2,3,4,5};
            int[] retArr = productPrevious(arr);

            for (int elem: retArr){
                System.out.print(elem + " ");
            }
        }

        public int[] productPrevious (int[] arr){
            int[] retArr = new int[arr.length];
            int product = 0;

            for (int i = 0; i < arr.length; i++){
                product = 0;
                for (int j = 0; j <= i; j++){
                    product *= arr[j];
                }
                retArr[i] = product;
            }
            return retArr;
        }

And this is my code. But I don't know why the elements in the output array are always zero.

Input: {1, 2, 3, 4, 5}

Output that I want: {1, 2, 6, 24, 120}

The output I'm getting: {0, 0, 0, 0, 0}

Is anything wrong with my code?

Upvotes: 0

Views: 147

Answers (2)

Doctor Who
Doctor Who

Reputation: 792

You are assigning product = 0 and product of 0 is always 0

initialize product to 1 will work fine like below

public static int[] productPrevious (int[] arr){
        int[] retArr = new int[arr.length];
        int product = 0;
        for (int i = 0; i < arr.length; i++){
            product = 1;
            for (int j = 0; j <= i; j++){
                product *= arr[j];
                System.out.println(product);
            }
            retArr[i] = product;
        }
        return retArr;
    }

Upvotes: 1

rhino_rus
rhino_rus

Reputation: 140

Because of your product variable is 0 by default.

0 * (any other number) = 0

Set your product variable to 1 to fix problem.

Upvotes: 2

Related Questions