44. JAVA Program to find the Sum of Distinct Numbers.
How does this program work?
- In this program we are going to learn about how to find the Sum of N even numbers using java.
- The integer entered by the user is stored in variable n.
- Declare variable sum to store the sum of distinct numbers and initialize it with 0.
Here is the code
public class sum
{
static int findSum(int arr[], int n)
{
// sort all elements of array
Arrays.sort(arr);
System.out.println("Sum of Distinct numbers are:");
int sum = arr[0];
for (int i = 0; i < n-1; i++)
{
if (arr[i] != arr[i + 1])
{
sum = sum + arr[i+1];
}
}
return sum;
}
public static void main(String[] args)
{
int arr[] = {1, 2, 3, 2, 1, 4, 5, 6, 3, 8, 0};
int n = arr.length;
System.out.println(findSum(arr, n));
}
}