* 1008. Right Shift of array element loop, 1008 right shift
1/* 2 * Main. c 3*1008. array Element loop right shift problem Ver.2 4 * Created on: August 29, 2014 5 * Author: boomkeeper 6 ********* passed the test ******** 7 */8 # include <stdio. h> 9 10 int main (void) {11 12 int array [101]; 13 int n, m; // N, M14 int I, j In the question; 15 16 scanf ("% I", & n, & m); 17 getchar (); 18 19 for (I = 0; I <n; I ++) {20 scanf ("% I", & array [I]); 21} 22 // limit m to 0 ~ The range of n is 23 // while (m> n) {24 // m/= n; 25 //} 26 // shift right 27 int temp; 28 for (I = 0; I <m; I ++) {29 temp = array [n-1]; 30 for (j = n-2; j> = 0; j --) {31 array [j + 1] = array [j]; 32} 33 array [0] = temp; 34} 35 // output 36 for (I = 0; I <n; I ++) {37 if (I = 0) 38 printf ("% I", array [I]); 39 else40 printf ("% I ", array [I]); 41} 42 printf ("\ n"); 43 44 return 0; 45}
If the value of m is 0 ~ N range, an error will be reported when the question is submitted. In this case, if m> n, the loop is actually invalid for many times... it should be multiple loops (m/n) * n times...
1/* 2 * Main. c 3*1008. array Element loop right shift problem Ver.1 4 * Created on: August 29, 2014 5 * Author: in the Boomkeeper 6 ********* section, ******** 7 */8 # include <stdio. h> 9 10 int main (void) {11 12 int array [101]; 13 int n, m; // N and M14 int I in the question; 15 16 scanf ("% I", & n, & m); 17 getchar (); 18 19 for (I = 0; I <n; I ++) {20 scanf ("% I", & array [I]); 21} 22 // limit m to 0 ~ The range of n is 23 while (m> n) {24 m/= n; 25} 26 // output 27 for (I = n-m; I <n; I ++) {28 if (I = n-m) 29 printf ("% I", array [I]); 30 else31 printf ("% I", array [I]); 32} 33 for (I = 0; I <n-m; I ++) 34 printf ("% I", array [I]); 35 printf ("\ n"); 36 37 return 0; 38}
This algorithm is not completely passed. If the m range is not restricted, the array will be out of bounds.
Question link:
Http://pat.zju.edu.cn/contests/pat-b-practise/1008
.
1008 right shift of array element loop (20), answers
I. printf ("% d \ n", q [s]); add a carriage return here.
II,
For (j = a-B; j <a; j ++)
{
Printf ("% d", q [j]);
} When B = a, the last output here will contain spaces!
Use a pointer to move the array element to the right, and move the last element to the beginning.
# Include <stdio. h>
Main ()
{Int a [10], I, t;
For (I = 0; I <10; I ++)
Scanf ("% d", & a [I]);
T = a [9];
For (I = 9; I> 0; I --)
A [I] = a [I-1];
A [I] = t;
For (I = 0; I <10; I ++)
Printf ("% d \ n", a [I]);
}