Example 65: Rotate an Array
Learn how to rotate the contents of an array.
We'll cover the following
Problem
Write a function that rotates left the contents of a 1D array of integers by the desired number of places.
Example
Suppose an array named arr contains the following elements:
arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
The following table shows the output array once it has been rotated by k elements.
Input (arr, size, k) | Output |
---|---|
arr, 10, 2 | 3, 4, 5, 6, 7, 8, 9, 10, 1, 2 |
arr, 10, 5 | 6, 7, 8, 9, 10, 1, 2, 3, 4, 5 |
arr, 10, 10 | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
Demonstration
Get hands-on with 1400+ tech skills courses.