Array-promo

Question

Copy all the elements of one array into another array in reverse order.

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					
  import java.util.Scanner;
public class copyArraytoanotherArrayInReverseOrder
{  
    public static void main(String[] args)
    {  
        /* Initialize array */  
        int [] arr1;
        int[] arr2;
        int n=0,i=0;
        Scanner sc = new Scanner(System.in);    
        
        System.out.println("Enter a no. of elements in the array");   
        n = sc.nextInt(); 
        System.out.println("Enter numbers in array");
        arr1=new int[n];
        for(i=0;i< n;i++)
        {
            arr1[i]=sc.nextInt();
        }
        
         
        //Create another array arr2 with size of arr1  
         arr2 = new int[arr1.length];  
         int j=arr1.length-1;
        //Copying all elements of one array into another  in reverse order
        for ( i = 0; i < arr1.length; i++)
        {   
            arr2[i] = arr1[j];
            j--;
        }    
          
        /*Displaying elements of array arr1*/   
        System.out.println("Elements of original array: ");  
        for ( i = 0; i < arr1.length; i++)
        {   
           System.out.print(arr1[i] + " ");  
        }   
          
        System.out.println();  
          
        /*Displaying elements of array arr2 */  
        System.out.println("Elements of array in reverse order: ");  
        for ( i = 0; i < arr2.length; i++) 
        {   
           System.out.print(arr2[i] + " ");  
        }   
    }  
}    




				
			

Coding Store

10-minute Stress-Buster Games

Leave a Reply

Your email address will not be published. Required fields are marked *