Make new int array double the size of an array copy the first numbers and put others in reverse without using methods

Viewed 336

Lets say I input array {1,2,3,4} and I want to make a new one {1,2,3,4,4,3,2,1}.

import java.util.Scanner;

public class Task2 {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int[] arr = new int[4];

    for(int i = 0; i < arr.length; i++){
        System.out.println("Please enter number!");
        arr[i]=sc.nextInt();
    }

    int[] actualArr = new int[arr.length*2];

    for(int j = 0; j < arr.length; j++){
        actualArr[j]=arr[j];
    }

    for (int k = arr.length - 1; k >= 0; k--) {    //problem loop
        actualArr[arr.length] = arr[k];
    }

    for (int g = 0; g < actualArr.length; g++) {
        System.out.print(actualArr[g] + " ");
    }
  }
}

Why do I get 1 2 3 4 1 0 0 0 ? My int k starts from 3 but I get the [0] index from int[]arr which is 1 and not the last which is 4, also how can i copy the rest of the first array in reverse order?

2 Answers

Your problem is on this line insithe the for loop:

actualArr[arr.length] = arr[k];

arr.length will always be 4, so you will always update the 5th element (element at index 4 because arrays are zero-based in Java) in your actualArr array leaving the remaining slots of the array with the default int value 0. Look how actualArr changes on each iteration of that loop:

actualArr = {1, 2, 3, 4, 4, 0, 0, 0} // 1st iteration
actualArr = {1, 2, 3, 4, 3, 0, 0, 0} // 2nd iteration
actualArr = {1, 2, 3, 4, 2, 0, 0, 0} // 3rd iteration
actualArr = {1, 2, 3, 4, 1, 0, 0, 0} // 4th iteration and final output

You can do this to fill the array correctly:

for (int k = arr.length - 1; k >= 0; k--) {
    actualArr[actualArr.length - k - 1] = arr[k];
}

The expression actualArr.length - k - 1 will result in a sequence from 4-7 filling the array as you want.

You may can define a new integer like z and z is initial for your new array (actualArr):

int[] actualArr = new int[arr.length*2];
int z=0;
for(int j = 0; j < arr.length; j++){
    actualArr[z]=arr[j];
    z++;
}

for (int k = arr.length-1 ; k >= 0; k--) {    //problem loop
    actualArr[z] = arr[k];
    z++;
}
Related