Day 5: #Java #Coding #Array 👉 yesterday I posted the question. today I will post the answer 👉 This line imports the Scanner class. Scanner is used to take input from the user 👉 Declares your class name. Java program always runs inside a class. 👉 This isthe starting point of execution. JVM starts running your program from here. 👉Creates a Scanner object. System.in → means input comes from keyboard. 👉 Prints message to user. Takes input (size of array). Example: if user enters 5, array size = 5. 👉 Creates an integer array a. Size is decided by user. 👉 Loop runs from 0 to size-1. Stores user input into array. 👉 step 1: Count Unique Elements int count=0; 🔸 Outer loop → picks each element. for(int i = 0; i < a.length; i++) 🔸 Assume element is not duplicate. boolean ispresent = false; 🔸 Inner loop → checks previous elements only. for(int k = 0; k < i; k++) 🔸 If current element already appeared before → duplicate. Set ispresent = true and stop checking. if(a[i] == a[k]) ispresent = true; break; 🔸 If element is not duplicate, increase count. if(!ispresent) count++; 🔸. New array b stores only unique values. index tracks position in array b. int[] b = new int[count]; int index = 0; 🔸Outer Loop This loop runs from 0 to last index of array a. i represents the current element index. for(int i = 0; i < a.length; i++) 🔸Initialize Flag Assume current element is not duplicate. This variable checks: 👉 “Is this element already seen before boolean ispresent = false; 🔸Inner Loop for(int k = 0; k < i; k++) This loop checks only previous elements. k runs from 0 to i-1. 🔸 Compare Elements if(a[i] == a[k]) Compare current element a[i] with previous element a[k]. 🔸 Duplicate Found ispresent = true; break; If match found: Mark ispresent = true (duplicate exists) break → stop checking further (no need) 🔸 Check if Unique if(!ispresent) ! means NOT So this means: 👉 “If element is NOT present before (unique)” 🔸 Store Unique Element b[index] = a[i]; Store the unique element into new array b. 🔸 Move Index index++; Move to next position in array b.

To view or add a comment, sign in

Explore content categories