fork download
  1. #include <stdio.h>
  2.  
  3. /* This is a tail-recursive version :-D */
  4. void shift_replace_rec(int *A, unsigned int len, unsigned int delta)
  5. {
  6. if (delta > 0)
  7. {
  8. unsigned int i = len-1;
  9.  
  10. /* Get the last element to eventually swap it with the first. */
  11. unsigned int temp = A[i];
  12.  
  13. /* Shift everything one block to the right. */
  14. for (; i > 0; --i)
  15. {
  16. A[i] = A[i-1];
  17. }
  18.  
  19. /* Last element is now the first element. */
  20. A[i] = temp;
  21.  
  22. /* Recurse! */
  23. shift_replace_rec(A, len, delta-1);
  24. }
  25. }
  26.  
  27. void print_array(const int *A, const unsigned int len)
  28. {
  29. int i;
  30. for (i = 0; i < 10; ++i)
  31. {
  32. printf("%d", A[i]);
  33. }
  34. putchar('\n');
  35. }
  36.  
  37. int main(int argc, char *argv[])
  38. {
  39. int A[] = {0,1,2,3,4,5,6,7,8,9};
  40. print_array(A, 10);
  41. puts("Shifting by 3...");
  42. shift_replace_rec(A, 10, 3);
  43. print_array(A, 10);
  44. puts("Shifting by 7... (Should be the original order now)");
  45. shift_replace_rec(A, 10, 7);
  46. print_array(A, 10);
  47. return 0;
  48. }
Success #stdin #stdout 0.01s 1720KB
stdin
Standard input is empty
stdout
0123456789
Shifting by 3...
7890123456
Shifting by 7... (Should be the original order now)
0123456789