C++ Tutorials

C++ Tutorials

Generate SubArrays using C++

The most efficient method to find all possible sub-array in a given array, Best algorithm to find all subarrays of a given array

Subarray in C++: A subarray is a contiguous part of array. An array that is inside another array.

#include<bits/stdc++.h>
#include<iostream>

using namespace std;

int main(){

int n;
cout<<"Enter a number of element array: ";
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
  cout<<"Enter "<<i+1<<" element: ";
  cin>>arr[i];
}
//Generate all SubArray
//Element of SubArray(i,j)
for(int i=0; i<n; i++){
  for(int j=i; j<=n; j++){
    for(int k=i; k<=j; k++){
      cout<<arr[k]<<",";
    }
    cout<<endl;
  }
}
return 0 ;
}
//Use three nested loops. 
{ 

 //select the starting element 

for (int i=0; i <n; i++) 

{ 

 //select the ending element 

for (int j=i; j<n; j++)

{ 

for (int k=i; k<=j; k++) 

{ 

//print all elements between start and end element.

cout << arr[k] << ", "; 

} 

cout << endl; 

//time complexity of this approach is O(n^3).

How do I get all the subarrays of an array?

Print all subarrays of a given array

  1. Use three nested loops.
  2. Outer loops will decide the starting point of a sub-array, call it as startPoint.
  3. The first inner loops will decide the group size (sub-array size).
  4. The most inner loop will actually print the sub-array by iterating the given array from startPoint and print the next group’s elements.