# Swift Program to Rotate Elements of an Array

In Swift, we create a user defined function to rotate the elements of an array. In this function, first we find the total number of rotation and then rotate the array by the specified number of rotation.

For example −

Array = [3, 5, 2, 1, 7, 9]
Rotation = 2
Resultant Array = [2, 1, 7, 9, 3, 5]


## Algorithm

• Step 1 − Create a function that rotate the elements of the array in the specified number of rotation.

• Step 2 − Inside the function first we find the required number of rotations.

• Step 3 − Then using the array slicing syntax we rotate the array according to the given rotation.

• Step 4 − Outside the function create an array.

• Step 5 − Now call the above created function and pass the array and the number of position to which the element shift.

• Step 6 − Print the output.

## Example

In the following swift example, we will first create a function named as rotateMyArray(), it takes two parameters array and the total number of position to shift the elements of the array. Now inside the function, we first find the required number of rotation and then using array slice we rotate the elements of the array. Now we create an array [3, 7, 1, 9, 3, 8, 4] and rotate it by 3 positions using rotateMyArray() function. So the resultant array is [9, 3, 8, 4, 3, 7, 1].

import Foundation
import Glibc

// Function to rotate the elements of the given array
func rotateMyArray(array: inout [Int], rotate: Int) {

// Calculate the required number of rotations
let mRotate = rotate % array.count

// Rotating the array by the specified number of rotations
array = Array(array[mRotate..<array.count] + array[0..<mRotate])
}

var myArray = [3, 7, 1, 9, 3, 8, 4]
print("Original Array:", myArray)

rotateMyArray(array: &myArray, rotate: 3)
print("Modified Array:", myArray)


## Output

Original Array: [3, 7, 1, 9, 3, 8, 4]
Modified Array: [9, 3, 8, 4, 3, 7, 1]


## Conclusion

So this is how we can rotate the elements of the array. Here we use inout parameters in the function. The inout keyword is used to pass a parameter in the function as a reference which means if any change made in the parameter can reflect in the original parameter.

Updated on: 24-Apr-2023

197 Views 