1
$\begingroup$
import java.io.*;
import java.util.*;
public class reverseAnArray2
{
    public static void main(String args[])throws IOException
    {
        Scanner sc  = new Scanner(System.in);
        System.out.println("Enter size");
        int  n = sc.nextInt();
        int a [] = new int [n] ;
        int b [] = new int [n] ;
        System.out.println("Enter elements");
        for(int i=0;i<n;i++)
        {
        
            a[i]=sc.nextInt() ;
        }
        int size = n;
        System.out.println("Reverse array is : ");
        int p=0;
        while(n>=0 && p<n)
        {
            
            a[--n] = a[p] ;
            ++p;
        }
        for(int i =0;i<size;i++)
        {
             System.out.println(+ a[i]);
        }
       
        
}
}

The output comes correct but only up to the last $n/2$ terms, rest of it gets repeated. The output was correct when I used another fresh array to store data. But that's not an optimal code. I want to reverse it without using another array.

$\endgroup$
1
  • 2
    $\begingroup$ "Please spot the problems in my code" questions are off-topic here. $\endgroup$
    – D.W.
    Apr 18 at 2:32
0
$\begingroup$

Notice that you increment $p$, whilst also decrementing $n$. Since your condition in the while loop is that p < n, then the while loop will only work for half the elements.

Also, note that you delete the last $n/2$ values, since you modify them without first reading them.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.