Ques 1
Ques 1
Algorithm:
Source Code:
import java.util.Scanner;
class Collection {
int ar[] = new int[100]; // Array to store elements
int len = 0; // Length of the array
Collection() {
len = 100; // Default constructor sets length to 100
}
Collection(int length) {
len = length; // Parameterized constructor sets length to given value
}
void input() {
Scanner sc = new Scanner(System.in); // Create Scanner object for input
System.out.println("Enter array elements, one by one:"); // Prompt user for input
for (int l = 0; l < len; l++)
ar[l] = sc.nextInt(); // Read array elements
sc.close(); // Close Scanner
}
Collection common(Collection obj) {
Collection comm = new Collection(); // Create new Collection for common elements
int k = 0; // Index for common elements array
for (int i = 0; i < len; i++) // Loop through current array
for (int j = 0; j < obj.ar.length; j++) // Loop through passed array
if (ar[i] == obj.ar[j]) {
comm.ar[k] = ar[i]; // Store common element
k++; // Increment index
}
return comm; // Return common elements Collection
}
void display() {
for (int m = 0; m < len; m++)
System.out.println(ar[m]); // Print array elements
}
public static void main(String[] args) {
System.out.println("Enter number of elements in array 1:");
Scanner sc = new Scanner(System.in); // Create Scanner for input
Collection arr1 = new Collection(sc.nextInt()); // Create first Collection
arr1.input(); // Input elements for first Collection
System.out.println("Enter number of elements in array 2:");
Collection arr2 = new Collection(sc.nextInt()); // Create second Collection
arr2.input(); // Input elements for second Collection
Collection common = new Collection(); // Create Collection for common elements
common = arr1.common(arr2); // Find common elements
System.out.println("Array 1:");
arr1.display(); // Display elements of first array
System.out.println("Array 2:");
arr2.display(); // Display elements of second array
System.out.println("Common Elements:");
common.display(); // Display common elements
}
}
Variable Data
Description
Name Type
ar int[] Stores the elements of the array
len int Stores the length of the array
sc Scanner Reads input from the user
l int Loop counter for reading elements into ar
obj Collection The Collection object passed to the common method
comm Collection Stores the common elements
k int Index for storing common elements in comm.ar
i int Loop counter for iterating over this.ar
j int Loop counter for iterating over obj.ar
m int Loop counter for printing elements of ar
arr1 Collection First Collection object
arr2 Collection Second Collection object
common Collection Stores the common elements between arr1 and arr2
len1 int Stores the length of the first array
len2 int Stores the length of the second array
Output Screen: