create two arrays in java A and B of size 5 and C of size 10.Accept numbers in two arrays A and B.fill the array in such a way that all odd positions occupy the numbers present in array and all even positions occupy the numbers present in array B.
Answers
Question:-
Write a program in Java to create arrays A, B and C of size 5,5 and 10. Accept numbers in two arrays A and B and fill the array in such a way that all the odd position occupy the numbers present in array A and all even positions occupy the numbers present in array B.
Program:-
This is a very nice question. I will try to solve it in a simple and easy way.
So, here is the program. (Using 3 loops).
import java.util.*;
class Array
{
public static void main(String args[])
{
// declaring arrays A, B and C.
int A[]=new int[5], B[]=new int[5], C=new int[10];
Scanner sc=new Scanner(System.in);
System.out.println("Enter the elements of Array A. ");
for(int i=0;i<5;i++)
{
System.out.print("Enter: ");
A[i]=sc.nextInt();
}
System.out.println("Enter the elements of Array B. ");
for(int i=0;i<5;i++)
{
System.out.print("Enter: ");
B[i]=sc.nextInt();
}
for(int i=0;i<10;i++)
{
if(i%2==0) // odd position.
C[i]=A[i];
else
C[i]=B[i];
}
System.out.println("New Array is... ");
for(int i=0;i<10;i++)
System.out.print(C[i]+" ");
}
}