/* rotate.cpp - We rotate an array using the
		reverse function. Motivated by Bentley's Programming
		Pearls. Notice how easy is the program and how we
                can rotate an array without need for extra storage.
 */

#include <iostream>
#include <iomanip>
using namespace std;


// Print an integer array with n elements k per line
void printk(const int a[], int n, int k)
{
   int pos = 0;
   for (int h = 0; h < n; h++) {
      cout << setw(10) << a[h];
      if (++pos == k) {
	 cout.put('\n');
	 pos = 0;
      }
   }
   if (pos > 0)
      cout.put('\n');
}

// reverse the content of the array a
// with n elements
void reverse (int a[], int n)
{
   for (int k = 0; k < n/2; ++k) {
      int temp = a[k];
      a[k] = a[n-k-1];
      a[n-k-1] = temp;
   }
}

// Rotate the array a with n elements k
// positions to the left 
void rotate (int a[], int n, int k)
{
   k = k % n;
   reverse(a, n);
   reverse(a, n-k);
   reverse(a+n-k, k);
}


int main()
{
   int a[] = {1,2,3,4,5,6,7,8,9};
   printk(a, 9, 3);
   for ( ; ; ) {
      int b[9] = a;
      cout << "Enter an integer: ";
      int k;
      cin >> k;
      if (k == 0) break;
      rotate(b, 9, k);
      printk(b, 9, 3);
   }
   return 0;
}