-1

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
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 2
    Do note that `int arr[n];` is a variable length array (VLA) and is not standard C++. You can directly replace it with a vector like `std::vector arr(n);` to have portable code. – NathanOliver Jul 18 '19 at 13:03
  • 1
    **Recommended reading:** [Why should I not #include ?](https://stackoverflow.com/q/31816095/560648) – Lightness Races in Orbit Jul 18 '19 at 13:14

2 Answers2

2

You also need to reset the count. In addition to that, the my_nums vector should be cleared after printing the elements in it.

count++;
if (count == k)
{
    for (auto it = my_nums.rbegin(); it != my_nums.rend(); ++it)
    {
        cout << *it << " ";
    }
    my_nums.clear();  // moved to here
    count = 0;   // --> reset here
}

But what happens when the count < k but i >= n ? That means you need to print the my_nums again after the for loop if my_nums is not empty, in order to get the complete result.

for (int i = 0; i < n; i++)
{
    // above code
}

if (!my_nums.empty())
{
    for (auto it = my_nums.rbegin(); it != my_nums.rend(); ++it)
    {
        cout << *it << " ";
    }
}

Also, note that followings:

JeJo
  • 30,635
  • 6
  • 49
  • 88
1

Try to set "count = 0" at the end on the outer loop.

yxc
  • 11
  • 1