Answer to Question #155947 in C++ for Usman

Question #155947

Write a C++ program in which, read data from user into an integer array and an integer n. now rotate the array n times. 



1
Expert's answer
2021-01-18T04:34:55-0500
// this programm do Right rotate an array k times
#include <iostream>
// Function to right rotate an array by one position
void rightRotateByOne(int A[], int n)
{
    int last = A[n - 1];
    for (int i = n - 2; i >= 0; i--)
        A[i + 1] = A[i];
 
    A[0] = last;
}
// Function to right rotate an array by k positions
void rightRotate(int A[], int k, int n)
{
    for (int i = 0; i < k; i++)
        rightRotateByOne(A, n);
}
using namespace std;
int main () {
    int len;
    cout << "Enter the number of elements in array: \n";
    cin >> len;
    int array[len];
    cout << "Enter array elements: \n";
    for (int i = 0; i < len; i++) {
        cout << "array[" << i << "] = ";
        cin >> array[i];
    }
    cout << "\nBefore rotating: \n";
    for (int i = 0; i < len; i++) {
        cout << array[i] << " ";
    }
    cout << "\nHow many times the array ms be rotate: \nk = ";
    int k;
    cin >> k;
    int n = sizeof(array)/sizeof(array[0]);
    rightRotate(array, k, n);
    cout << "\nAfter rotating: \n";
    for (int i = 0; i < len; i++) {
        cout << array[i] << " ";
    }
    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