Write a program that include the following function: void insert0(int n, int a1[
ID: 3791590 • Letter: W
Question
Write a program that include the following function:
void insert0(int n, int a1[], int a2[]);
that has as input an integer array a1[] of length n and as output an integer array a2[] of length 2n. The function copies the input array to the output array, inserting the value 0 between each copied value. Thus, if a1[] contains the values -9, 16, 0, 2, the output array a2[] should have the values -9, 0, 16, 0, 0, 0, 2, 0.
In the main function, ask the user to enter the length of the input array, declare the input and output arrays, read in the values for the input array, and call the insert0 function to compute the output array. The main function should display the result of the output array.
Enter the length of the array: 5
Enter the elements of the array: 3 4 9 1 4
Output:
The output array is: 3 0 4 0 9 0 1 0 4 0
Explanation / Answer
import java.util.Arrays;
import java.util.Scanner;
public class insertO {
public static void main(String[] args) {
System.out.print("Enter the length of the array:");
Scanner scanner=new Scanner(System.in);
int length=scanner.nextInt();
System.out.print("Enter the elements of the array:");
int[] inputArray=new int[length];
for(int i=0;i<length;i++){
inputArray[i]=scanner.nextInt();
}
System.out.print("Output: ");
System.out.print("The Output Array is:");
int[] outputArray=new int[2*length];
for(int i=0;i<outputArray.length;i++){
if(i%2==1){
outputArray[i]=0;
}else{
outputArray[i]=inputArray[i/2];
}
}
System.out.print(Arrays.toString(outputArray));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.