Write a method named copyRange that takes as parameters two arrays a1 and a2, tw
ID: 3763749 • Letter: W
Question
Write a method named copyRange that takes as parameters two arrays a1 and a2, two starting indexes i1 and i2, and a length l, and copies the first l elements of a1 starting at index i1 into array a2 starting at index i2. For example, if the following arrays are declared: int[] a1 = {10, 20, 30, 40, 50, 60}; int[] a2 = {91, 92, 93, 94, 95, 96}; copyRange(a1, a2, 0, 2, 3); After the preceding call, the contents of a2 would be {91, 92, 10, 20, 30, 96}. You may assume that the parameters' values are valid, that the arrays are large enough to hold the data, and so on.
Explanation / Answer
Here is the code for you in java. If you have any further queries, just revert to me.
import java.io.*;
import java.util.*;
class CopyRange
{
public static void copyRange(int a1[], int a2[], int i1, int i2, int l)
{
for(int i = 0; i < l; i++)
a2[i2+i] = a1[i1+i];
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] a1 = {10, 20, 30, 40, 50, 60};
int[] a2 = {91, 92, 93, 94, 95, 96};
System.out.print("Array1: ");
for(int i = 0; i < 6; i++)
System.out.print(a1[i]+" ");
System.out.println();
System.out.print("Array2: ");
for(int i = 0; i < 6; i++)
System.out.print(a2[i]+" ");
System.out.println();
System.out.print("Enter the index of matrix a1 to copy from: ");
int i1 = sc.nextInt();
System.out.print("Enter the index of matrix a2 to copy to: ");
int i2 = sc.nextInt();
System.out.print("Enter the number of elements to copy: ");
int l = sc.nextInt();
copyRange(a1, a2, i1, i2, l);
System.out.print("Array1: ");
for(int i = 0; i < 6; i++)
System.out.print(a1[i]+" ");
System.out.println();
System.out.print("Array2: ");
for(int i = 0; i < 6; i++)
System.out.print(a2[i]+" ");
System.out.println();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.