Search code examples
javaarrayscyclic

Java put one array into another


Hello guys it might be a dumb question but I am stuck. I am working on cyclic numbers code. After completing I put all the integers in the array however after that there are some empty cells at the beginning of array that have to be cleaned or put into another array with appropriate amount of elements. So how to get rid of 0 at the beginning.

Here is the code for my cyclic numbers:

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int carry = 0;

        int[] cyclic = new int[60];
        int lastDigit = input.nextInt();
        cyclic[cyclic.length - 1] = lastDigit;



            for ( int i = cyclic.length - 2; i >= 0; i--) {

                cyclic[i] = lastDigit * cyclic[i + 1];
                cyclic[i] += carry;
                if (cyclic[i] > 9) {
                    carry = cyclic[i] / 10;
                    cyclic[i] %= 10;
                } else
                    carry = 0;
                if (cyclic[i]==1 & cyclic[i+1]== 0)
                    break;
            }

            for (int j = 0; j < cyclic.length; j++)
                System.out.print(cyclic[j]);

Solution

  • You are filling the array of 60 elements [0 to 59] in reverse order i.e. from 59 then 58 and then 57 and so on.

    While printing you are printing it from indices 0,1,2 and so on.

    This is the 1st thing that you should fix fill them from 0,1,2 or print them from 59,58 and so on.

    The reason why you are getting 0 is when you say ,

    int[] cyclic = new int[60];
    

    cyclic has memory for 60 ints and all the 60 values are now initialized with 0. Primitive data types are initialized with 0 when you allocate memory to it. and that's why "the empty cells at the beginning of array" are showing 0 after printing.