Write a recursive void function called rotateLeft that rotates the first n integ
ID: 3544569 • Letter: W
Question
Write a recursive void function called rotateLeft that rotates the first n integers in an array to the left. To rotate n items left, rotate the first n-1 items left recursively, and then exchange the last two items. For example, to rotate the five items
50 60 70 80 90
to the left, recursively rotate the first four items to the left:
60 70 80 50 90
and then exchange the last two items:
60 70 80 90 50
Test it with a main program that takes as input an integer count followed by the values to rotate. Output the original values and rotates values. Do not use a loop in rotateLeft. Output the value in the main program, not in the procedure.
Sample Input
5 50 60 70 80 90
Sample Output
Original list: 50 60 70 80 90
Rotated list: 60 70 80 90 50
Explanation / Answer
#include <iostream>
using namespace std;
void rotateLeft(int *arr, int size)
{
if(size < 2)
return;
rotateLeft(arr,size-1);
int temp;
temp = arr[size-2];
arr[size-2] = arr[size-1];
arr[size-1] = temp;
}
int main()
{
int arrSize;
cout << "Input: ";
cin >> arrSize;
int array[arrSize];
for(int i = 0; i < arrSize; i++)
cin >> array[i];
cout << "Original list: ";
for(int i = 0; i < arrSize; i++)
cout << array[i] << " ";
cout << endl;
rotateLeft(array, arrSize);
cout << "Rotated list: ";
for(int i = 0; i < arrSize; i++)
cout << array[i] << " ";
cout << endl;
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.