This Java program prompts the user to enter the limits for two arrays, then asks for input to fill the arrays. It then uses nested loops to find and print out any elements that are common to both arrays. Here's how the program works:
Overall, this program is a simple example of how to use nested loops to compare elements in two arrays in Java. It is useful for beginners who are just learning how to use loops and arrays in Java.
import java.util.Scanner; import java.util.Arrays; public class Array_Common { public static void main(String[] args) { Scanner input =new Scanner(System.in); System.out.print("Enter the First Array Limit :"); int n =input.nextInt(); System.out.print("Enter the Second Array Limit :"); int m =input.nextInt(); int [] a =new int[n]; int [] b =new int[m]; for(int i=0;i<n;i++) { System.out.printf("Element of a[%d] :",i); a[i]=input.nextInt(); } for(int i=0;i<m;i++) { System.out.printf("Element of b[%d] :",i); b[i]=input.nextInt(); } System.out.println("Array1 : "+Arrays.toString(a)); System.out.println("Array2 : "+Arrays.toString(b)); System.out.println("\nCommon Array Element is..\n"); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if(a[i] == (b[j])) { System.out.println(a[i]); } } } } }
Enter the First Array Limit :5 Enter the Second Array Limit :5 Element of a[0] :10 Element of a[1] :20 Element of a[2] :30 Element of a[3] :40 Element of a[4] :50 Element of b[0] :10 Element of b[1] :30 Element of b[2] :60 Element of b[3] :50 Element of b[4] :70 Array1 : [10, 20, 30, 40, 50] Array2 : [10, 30, 60, 50, 70] Common Array Element is.. 10 30 50
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions