Reverse the elements in array

Simple java program to reverse content in array. Logic is easy, it can also be used in other programming languages such as c# sharp, php... Here the index is reversed so the elements in the array are reversed.

class Reversearray{
    public static void main(String args[])  {
  int[]  oldarray={4,5,6};
  int[] resultarray=new int[3];
int m=0;
int len=oldarray.length;
for(int i=len-1;i>=0;i--)
{
resultarray[m]=oldarray[i];
m++;
}
for(int i=0;i<  oldarray.length;i++)
{
System.out.println(resultarray[i]);
}
}
}

 

output:

6

5

4

Explanation:

for(int i=len-1;i>=0;i++)

In the above line, len variable will have value 3, length of the array.

Len-1 => 3-1 => 2. Index 2 of an array will have the value 6. It will be stored as 1 st element in resultarray (resultarray[0]=oldarray[2] ).