Reputation: 13
Does values in for loop gives boolean results in Java? Getting this error when I compiled the code:
prog.java:52: error: incompatible types: int cannot be converted to boolean for(int i=0;i=n/2;i++){
public static void reverseArray(int arr[], int n) {
// Your code here
int temp;
int i=0;
for(i=0;i=n/2;i++){
temp = arr[i];
arr[i]=arr[n-i];
arr[n-i]=temp;
}
}
Upvotes: -1
Views: 2978
Reputation: 19575
for
loop needs to be fixed to provide boolean expression: i < n/2
n - i - 1
as the array indexes in Java are zero-based: [0..n - 1]
make n
elements.Thus, the updated function may loo like this (with all relevant variable declarations moved inside for
loop):
public static void reverseArray(int[] arr, int n) {
for (int i = 0, j = n - 1; i < n/2; i++, j--) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Also, the implemented method allows to reverse a part of n
elements of the input array, so it may be better to have an overloaded version accepting only arr
argument, and use minimal value of n
and arr.length
to prevent ArrayIndexOutOfBoundsException
:
public static void reverseArray(int[] arr) {
reverseArray(arr, arr.length);
}
public static void reverseArray(int[] arr, int n) {
for (int i = 0, m = Math.min(n, arr.length), j = m - 1; i < m/2; i++, j--) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Test:
int[] arr = {1, 2, 3, 4, 5};
reverseArray(arr, 3);
System.out.println("After reverse: " + Arrays.toString(arr));
Output:
After reverse: [3, 2, 1, 4, 5]
Upvotes: 1