Print all subarrays of a given array

Problem: Given an array write an algorithm to print all the possible sub-arrays.

Example:

int [] a = {1, 2, 3};

Output: Possible subarrays –
{1}, {2}, {3}, {1, 2} , {2, 3}, {1, 2, 3}

Approach:

Click here to read about the recursive solution – Print all subarrays using recursion

  • Use three nested loops.
  • Outer loops will decide the starting point of a sub-array, call it as startPoint.
  • First inner loops will decide the group size (sub-array size). Group size starting from 1 and goes up array size. Let’s call is as grps.
  • The most inner loop will actually print the sub-array by iterating the given array from startPoint and print the next grps elements.
  • See the code below for more understanding.

Complete Code:


Output:

1
1 2
1 2 3
1 2 3 4
2
2 3
2 3 4
3
3 4
4