QUESTION
Given an array of distinct elements. The task is to find triplets in array whose sum is zero. Take the array as input.
“TESTCASE_1”: “0 -1 2 -3 1\n###—###SEPERATOR—###—\n0 -1 1\n2 -3 1”, “TESTCASE_2”: “1 -2 1 0 5\n###—###SEPERATOR—###—\n1 -2 1”, “TESTCASE_3”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0
ANSWER
import java.io.*;
import java.util.*;
class TestClass{
// Prints all triplets in arr[] with 0 sum
static void findTriplets(int[] arr, int n)
{
boolean found = true;
for (int i=0; i<n-2; i++)
{
for (int j=i+1; j<n-1; j++)
{
for (int k=j+1; k<n; k++)
{
if (arr[i]+arr[j]+arr[k] == 0)
{
System.out.print(arr[i]);
System.out.print(" ");
System.out.print(arr[j]);
System.out.print(" ");
System.out.print(arr[k]);
System.out.print("\n");
found = true;
}
}
}
}
// If no triplet with 0 sum found in array
if (found == false)
System.out.println(" not exist ");
}
// Driver code
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int i=0;
int arr[]=new int[10];
while(in.hasNext())
{
arr[i]=in.nextInt();
i++;
}
int n =arr.length;
findTriplets(arr, i);
}
}