Answer to Question #346532 in C++ for Anonymous

Question #346532

Given a set of 'n' elements and 'r', write a generic function (Numbers and characters) to right shift the set of elements by 'r' position . If the elements are moved to the position that is greater than ‘n’ then wrap the shift process to the beginning of the collection.

For example, if the set of five elements are 1,7,8,9,12 and value of 'r' is 3 then the set of elements would be 8, 9, 12, 1, 7. 


1
Expert's answer
2022-05-31T10:03:56-0400
#include <iostream>
using namespace std;
 
 
// Function to print an array
void printArray(int arr[], int size) {
    int i;
    for (i = 0; i < size; i++)
    cout << arr[i] << " ";
    cout << endl;
}

void rotate(int arr[], int n) {
    int x = arr[n - 1], i;
    for (i = n - 1; i > 0; i--)
    arr[i] = arr[i - 1];
    arr[0] = x;
}
 
int main() {
    const int n=5;
    int r=3,i;
    int arr[n]={1,7,8,9,12};

    cout << "array: \n";
    printArray(arr, n);
    
    for(i=1; i<=r; i++){
        rotate(arr, n);            
    }
    
   
    cout << "Rorated array: \n";
    printArray(arr, n);
    cout<<endl;
    
return 0;
}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS