Core Java Array interview questions on the identification of multiple sub arrays within in the Array Input whose array elements sum is Zero.
Program Logic:
– Java Array provided with the list of array elements.
* Traverse the elements to identify if the value of that element is zero.
* Traverse the elements to identify if the value of multiple array elements sums up to Zero
* Print each such occurrence as an sub-array
package core.java.oracleappshelp.array;
public class identifySubArrayInArrayWithSumZero {
// Function to print all sub-arrays with 0 sum present
// in the given array
public static void identifySubArrayToDisplay(int[] ArrayWithAllElements)
{
// Traverse for the sub- array through the outerLoop
for (int outerLoop = 0; outerLoop < ArrayWithAllElements.length; outerLoop++)
{
int sum = 0;
// Traverse for the sub- array through the innerLoop
for (int innerLoop = outerLoop; innerLoop < ArrayWithAllElements.length; innerLoop++)
{
// adding value for innerLoop and outerLoop to get total sum value.
sum += ArrayWithAllElements[innerLoop];
// validate if the array index for innerLoop and OuterLoop sums up to 0
if (sum == 0) {
System.out.println("Subarray [" + outerLoop + ".." + innerLoop + "]");
}
}
}
}
public static void main (String[] args)
{
int[] A = { -2, 2, 1, 5, -6, 3, 1, -4, };
identifySubArrayToDisplay(A);
}
}