This Java program counts the number of unique absolute values in an array of integers. The program uses a HashSet to keep track of the absolute values seen so far, and increments a counter count every time a new absolute value is encountered.
The program first creates an array of integers num, which contains a mix of positive and negative numbers. It then initializes the counter count to zero and creates an empty HashSet called set.
The program then loops through each element of the array num, taking the absolute value of each element using the Math.abs() method. If the absolute value is not already in the set, the program adds it to the set and increments the count. Finally, the program prints the count of unique absolute values to the console.
Note that the program uses curly braces to create a block of code within the main method. This is not strictly necessary, since there is only one statement inside the block, but it is a common programming convention to use curly braces for clarity and consistency.
import java.util.*; import java.math.*; public class Count_Absolute { public static void main(String[] args) { { int[] num = new int[] { -1, -1, 10, 2, 2, 3, -41, 1, 5, 9 }; int count = 0; HashSet < Integer > set = new HashSet < Integer > (); for (int i = 0; i < num.length; i++) { int n = Math.abs(num[i]); if (!set.contains(n)) { set.add(n); count++; } } System.out.println(count); } } }
7
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions