How to Print an All Subarray of an Array

Prajwal
2 min readJan 11, 2023

--

Before diving into the problem, we must first grasp what the term “subarray” means.

What exactly is a subarray?

Subarrays are the continuous part of an array.

Let’s take an example: We are given an array, and we must print all of its subarrays.

→ int arr[] = {1,2,3,4,5}

📌The subarrays of the given arrays are ⤵️

📌Algorithm For the problem ⤵️

  • We will use three loops to print subarrays.
  • The outer loop will be used to get the start index
  • The first inner loop will be used to get the end index
  • The second inner loop will be used to print elements from the start to end index.

How do we print all Subarrays?

We are given an array arr = {1,2,3,4,5}

As you can see in the subarray, there is a repeating pattern. First, we create subarrays that begin with 1, then 2, then 3, and so on.

To get the first element of a subarray, we must loop through an array.

We can now find the last element of a subarray by looping inside the first element loop again to get the last element. We must begin the loop at the first element position.

To get the subarrays, we must loop from beginning to end and print all the elements in that range.

Code in java⤵️

public static void printSubarrays(int numbers[]) {
for (int i = 0; i < numbers.length; i++) {
for (int j = i; j < numbers.length; j++) {
for (int k = i; k <= j; k++) {
System.out.print(numbers[k] + " ");
}
System.out.println();
}
System.out.println();
}
}

Code in C++⤵️

void printSubarrays(int numbers[]) {
for (int i = 0; i < numbers.length; i++) {
for (int j = i; j < numbers.length; j++) {
for (int k = i; k <= j; k++) {
cout<<numbers[k]<< " ";
}
cout<<endl;
}
cout<<endl;
}
}

--

--

Prajwal

Engineering Student 🏫|| Front end developer || web3 enthusiast 🍃