leon
leon

Reputation: 1

i want fix my method to reverse int array

trying to write a method reverseIntArray(int[] array) which should return a reverse copy of an integer array. For example, if array = [1,2,3,4], then the method should return the array [4,3,2,1].

The program compiles without any error messages. What are the errors causing incorrect incorrect behavior of the program at runtime?

public static int[] reverseIntArray(int[] array) { 
    int[] result = new int[10];
    int j = array.length;
    for (int i = 1; i < array.length; i++ ) {
        result[i] = array[j];
        j++;
    } 
    return result; 
}

how should the error be corrected? what exactly is the error? what effect the error would have?

Upvotes: 0

Views: 124

Answers (3)

Manoj Kumar Dhakad
Manoj Kumar Dhakad

Reputation: 1892

To solve array related problem you must know only about its storage in memory and its index.

In your solution you are trying to overwrite values. In your solution you need to make sure that you are saving older value before writing any new value to any index.

NOTE: You must know that how to swap two numbers.

        int[] arr={1,2,3,4};
        int i=0;
        int j=arr.length-1;
        while(i<j)
        {
            //Swapping two numbers
            int temp=arr[i];
             arr[i]=arr[j];
            arr[j]=temp;
            i++;
            j--;
        }

You can also do the same using for loop.

Upvotes: 0

user9791370
user9791370

Reputation: 339

You need to set j to be array.length -1 instead of array.length and decrement it instead of incrementing it, and start your for loop index at 0 not 1.

Upvotes: 1

Hei2
Hei2

Reputation: 44

There are a couple of issues with your code:

  1. Your result array is being created with a size of 10 rather than the size of the array being passed in. This will cause an issue if you pass in an array with a smaller or larger size than 10. You can resolve this with: int[] result = new int[array.length];
  2. You're initializing i with a value of 1. Java arrays start at index 0, so your loop will skip populating the first element of the array. You instead want: for (int i = 0; i < array.length; i++) {
  3. Because java arrays start at index 0, the last element's index will be 1 less than array's size. You want: int j = array.length - 1;
  4. You want to retrieve array's elements in reverse order, but your code is incrementing j rather than decrementing it. You want j-- where you have j++

Upvotes: 0

Related Questions