Write a program to copy the elements of one array into another array


This is a Java program that creates a copy of an array entered by the user. Here is a step-by-step explanation of how the program works:

  • The program starts by importing the java.util.Scanner class, which is used to read user input from the console.
  • The Array_Copy class is defined, which contains the main method that will be executed when the program runs.
  • Inside the main method, a Scanner object is created to read user input.
  • The user is prompted to enter the array limit, which is the maximum number of elements that the array can hold. The user input is stored in the l variable.
  • Two integer arrays a and c of size l are created. a will hold the original array entered by the user, and c will hold the copy of the array.
  • A for loop is used to prompt the user to enter each element of the array. The loop iterates l times, and for each iteration, the user is prompted to enter an integer value, which is then stored in the corresponding index of the array a.
  • Another for loop is used to copy the elements of a into c. For each index i, the element at index i of a is copied into the corresponding index i of c.
  • The program then prints out the original elements of the array a and the copied elements of array c.
  • The program ends.

Source Code

import java.util.Scanner;
class Array_Copy
{
	public static void main(String[] args)
	{   
		Scanner input =new Scanner(System.in);
		System.out.print("Enter the Array Limit :");
		int l =input.nextInt();
		int [] a =new int[l];
		int [] c =new int[l];
		int sum = 0;
		for(int i=0;i<l;i++)
		{
			System.out.printf("Element of a[%d] :",i);
			a[i]=input.nextInt();
		}
		for(int i=0;i<l;i++)
		{
			c[i] = a[i];
		}
		System.out.print("\nOriginal Array Elements...");	
		for(int i=0;i<l;i++)
		{
			System.out.printf("\na[%d] = %d",i,a[i]);
		}
		System.out.print("\n\nCopy Array Elements one to Another Array...");	
		for(int i=0;i<l;i++)
		{
			System.out.printf("\nc[%d] = %d",i,c[i]);
		}
    }
}
 

Output

Enter the Array Limit :5
Element of a[0] :5
Element of a[1] :4
Element of a[2] :3
Element of a[3] :2
Element of a[4] :1

Original Array Elements...
a[0] = 5
a[1] = 4
a[2] = 3
a[3] = 2
a[4] = 1

Copy Array Elements one to Another Array...
c[0] = 5
c[1] = 4
c[2] = 3
c[3] = 2
c[4] = 1

Example Programs