🔗 Find Common Numbers Between Two Arrays (Java)
🧩 What problem are we solving?
Given two arrays of integers, the goal is to find and print all the numbers that appear in both arrays — i.e., the common elements or intersection of the two arrays.
For example:
If we have
then the numbers common to both are 12, 15, and 17.
⚙️ How it works (step by step)
-
Start with two arrays of integers.
-
Loop through each element of the first array (
array1). -
For each element in
array1, loop through the second array (array2). -
If a match is found (
array1[i] == array2[j]), print or store that number. -
Continue until all elements have been compared.
This approach compares every element in array1 with every element in array2, ensuring all common numbers are identified.
🧠Example Walkthrough
| Step | Compare | Match? | Common Numbers Found |
|---|---|---|---|
| 1 | 12 vs 12 | ✅ | 12 |
| 2 | 13 vs all | ❌ | 12 |
| 3 | 14 vs all | ❌ | 12 |
| 4 | 15 vs 15 | ✅ | 12, 15 |
| 5 | 16 vs all | ❌ | 12, 15 |
| 6 | 17 vs 17 | ✅ | 12, 15, 17 |
✅ Output:
package com.vinod.test;
/**
* Class to find common numbers from two arrays
*
*@authorvinodkariyathungalkumaran
*
*/
public class FindCommonNumbers {
public static void main(String[] args) {
int array1[] = { 12, 13, 14, 15, 16, 17 };
int array2[] = { 12, 18, 29, 15, 7, 17 };
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
System.out.println(array1[i]);
}
}
}
}
}
Output
12
15
17
No comments:
Post a Comment