Print all subarrays of a given array

Objec­tive:  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:

  • Use nested loops.
  • Outer loops will decide the starting point.
  • First inner loops will decide the group size. Starting from 1 and goes up array size.
  • Most inner loop will create the sub arrays and print it.
  • 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

__________________________________________________
Top Companies Interview Questions..-

GoogleMicrosoftAmazonFacebookmore..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

2 Responses

  1. Harsha Vardhan says:

    {1,3} is sub array I think

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: