Hi Sankar Sridhar, hope you are doing well
First as Houcem Eddin Hrichi said
Houcem Eddin Hrichi wrote: Also just a small remark, the program that you are writing isn't really "Revering an Array" it is more accurately "Printing array elements in reversed order", reversing an array would actually be repositioning the elements in the array cells in reversed order.
You are printing the array in reverse order.
When you encounter an exception try to search what it is then it becomes easier to fix.
An exception in Java is an event that occurs during the execution of a program and disrupts its normal flow(Google).
Sankar Sridhar wrote:
// Attempt to reverse
System.out.println("Reversed array:");
for(int i = 0; i < n; i++) {
System.out.print(arr[n - i] + " ");
}
I am getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException means that you are using an illegal index on array.
Array uses indexes to access its elemets.
Indexes start from 0.
Suppose that the "n" in your code is 5 (five elements).
With indexes you can access your elements in array, these are 0,1,2,3,4 = 5 elements.
On first step of execution of loop you are accessing array with index 5 because n - i = 5 - 0;
If you want to fix this error initialize variable "i" starting with 1 and try to use <= symbol on condition to access first element.
I hope you understood something.