Broad Network


3.6 Reverse Array in Groups in C

Basic Array Algorithm Problems in C

Full Course on Data Structures and Algorithms in C

By: Chrysanthus Date Published: 3 Feb 2026

The reader is advised to read all the lessons (tutorials) in this full course, in the order presented.

Problem

Given an array, arr[] and an integer k=3, find the array after reversing every sub-array of consecutive k elements in place. If the last sub-array has fewer than k elements, reverse it as it is. Modify the array in place; do not return anything. The given array is:

    [0, 1, 2, 3, 4, 5, 6, 7]  

The algorithm should use O(n) time and O(n) space. The output should be:

    [2, 1, 0, 5, 4, 3, 7, 6]  

Solution

Edge Cases:

When k = 1, or k = 0, the array stays the same.
When k is greater than or equal to the array size, the whole array is reversed. 

Strategy

- Take the first edge case into consideration.
- Begin from index 0 and find the size of the current sub-array to be reversed. If the number of elements is less than k, reverse all of them.
- Each sub-array is reversed using two pointers (optionally) that start from the two corners of the sub-array.

In the function there is the principal for-loop, where increment of the index is done in k's.

Zero based indexing is used. The left included index of a group (sub-array) is obtained from,

    int left = i;

where i is the iterating index. The right included index of a group (sub-array) is obtained from,

    i+k-1    //zero based counting

where i is the iterating index (zero based).

The following program illustrates this (read through the code and comments):

#include <stdio.h>

void reverseArrayInGroups(int arr[], int n, int k){
    for (int i = 0; i < n; i += k) {
        int left = i;
        int right;
    
        // to determine right value
        if(i+k-1 < n-1)
            right = i+k-1;    //zero based indexing
        else
            right = n-1;    //zero based indexing

        // reverse the sub-array [left, right]
        while (left < right) {
            // swap
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;

            left++;
            right--;
        }

    }
}

int main(int argc, char **argv)
{
    int arr[] = {0, 1, 2, 3, 4, 5, 6, 7};
    int k = 3;
    int n = sizeof(arr) / sizeof(arr[0]);    //divide size of array by size of one (first) element

    reverseArrayInGroups(arr, n, k);
  
    for (int i = 0; i < n; i++) 
        printf("%i ", arr[i]);
    printf("\n");
    
    return 0;
}

The output is:

    2 1 0 5 4 3 7 6 

Thanks for reading.





Related Links

More Related Links

Cousins

BACK NEXT

Comments


Note: You can use the Search Box above to find articles and discussions of interest.