I am given an array of n
elements and an integer K
is given. I have to print the sub-array of K
elements in reverse order.
I am storing the elements in a vector and increasing the count. Once the count equals K
, print the vector in reverse order and clear all the elements of the vector.
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t; // No of test cases
cin >> t;
while (t--)
{
// Size of array and The size of each group
int n, k;
cin >> n >> k;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
vector <int> my_nums;
int count = 0;
for (int i = 0; i < n; i++)
{
my_nums.push_back(arr[i]);
count++;
if (count == k)
{
for (auto it = my_nums.rbegin(); it != my_nums.rend(); ++it)
{
cout << *it << " ";
}
//Clear all elements in vector
my_nums.clear();
}
}
cout << endl;
}
return 0;
}
ex:
I/P:
1
8 3
1 2 3 4 5 6 7 8
Expected O/P:
3 2 1 6 5 4 8 7
Actual O/P:
3 2 1