The following method of printing all subarrays(contiguous subsequences) of an array is faster as compared to the general method of using three nested for loops:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> array;
int N;
std::cin >> N; //size of array
for (int i = 0; i < N; i++) {
int x;
std::cin >> x;
array.push_back(x);
}
int i = array.size() - 1;
std::vector<int> subarray=array;
do {
std::cout << subarray[array.size()-i-1] << " ";
if (i == 0) {
subarray.pop_back();
if (subarray.empty()) {
array.pop_back();
subarray=array;
}
std::cout << '\n';
i = subarray.size() - 1;
} else {
i--;
}
} while (i >= 0);
}
Can the do while loop be optimized further?