import java.util.*;
public class Reverse {
public static void main(String[] args) {
int n,i,j,temp;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int a[] = new int[n];
for(i=0; i<n; i++)
{
a[i] = sc.nextInt();
}
for(i=0;i<a.length/2;i++)
{
temp=a[i];
a[i]=a[a.length-i-1];
a[a.length-i-1]=temp;
}
System.out.println("The array after reverse is");
for(i=0; i<n; i++)
{
System.out.print(a[i]+ " ");
}
}
}
Another method :
import java.util.*;
public class Reverse {
public static void main(String[] args) {
int n,i,j,temp;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int a[] = new int[n];
for(i=0; i<n; i++)
{
a[i] = sc.nextInt();
}
j = i - 1;
i = 0;
while(i<j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
System.out.println("The array after reverse is");
for(i=0; i<n; i++)
{
System.out.print(a[i]+ " ");
}
}
}
i/p 6
1 2 3 4 5 6
o/p: The array after reverse is
6 5 4 3 2 1
public class Reverse {
public static void main(String[] args) {
int n,i,j,temp;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int a[] = new int[n];
for(i=0; i<n; i++)
{
a[i] = sc.nextInt();
}
for(i=0;i<a.length/2;i++)
{
temp=a[i];
a[i]=a[a.length-i-1];
a[a.length-i-1]=temp;
}
System.out.println("The array after reverse is");
for(i=0; i<n; i++)
{
System.out.print(a[i]+ " ");
}
}
}
Another method :
import java.util.*;
public class Reverse {
public static void main(String[] args) {
int n,i,j,temp;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int a[] = new int[n];
for(i=0; i<n; i++)
{
a[i] = sc.nextInt();
}
j = i - 1;
i = 0;
while(i<j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
System.out.println("The array after reverse is");
for(i=0; i<n; i++)
{
System.out.print(a[i]+ " ");
}
}
}
i/p 6
1 2 3 4 5 6
o/p: The array after reverse is
6 5 4 3 2 1
No comments:
Post a Comment