Write a method called append that accepts two integer arrays as parameters and r
ID: 3781442 • Letter: W
Question
Write a method called append that accepts two integer arrays as parameters and returns a new array that contains the result of appending the second array's values at the end of the first array. For example, if arrays list 1 and list 2 store {2, 4, 6} and {1, 2, 3, 4, 5} respectively. the call of append (list 1, list 2) should return a new array containing {2, 4, 6, 1, 2, 3, 4, 5}. If the call instead had been append(list 2, list 1), the method would return an array containing {1, 2, 3, 4, 5, 2, 4, 6}.Explanation / Answer
import java.util.*;
import java.lang.*;
class AppendArrays
{
public static void main (String[] args)
{
int i;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of list1");
int size1 = scan.nextInt(); // enter size of list 1
int[] list1 = new int[size1];
System.out.println("Enter the size of list2");
int size2 = scan.nextInt(); // enter size of list 2
int[] list2 = new int[size2];
for(i=0;i<size1;i++)
{
list1[i] = scan.nextInt(); //input elements of list1
}
for(i=0;i<size2;i++)
{
list2[i] = scan.nextInt(); //input elements of list2
}
int[] list3 = append(list1,list2); //method call
for(i=0; i<list3.length; i++)
System.out.print(list3[i]+" "); //display elements of appended list
}
public static int[] append(int[] list1,int[] list2)
{
int[]list3 = new int[list1.length+list2.length];
int i,j;
for(i=0; i<list1.length; i++)
list3[i] = list1[i]; //put all elements of list1 to list3
for(j=0; j<list2.length; j++)
list3[i++]=list2[j]; //put all elements of list2 to list3 appended at index i
return list3;
}
}
output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.