方法一:双层循环,直接在要移动的数组中移动修改
#include<stdio.h>
void f(int a[], int t)
{
int temp;
for (int i = 0; i <= t; i++)
{
temp = a[0];
for (int j = 0; j<9; j++)
{
a[j] = a[j + 1];
}
a[9] = temp;
}
for (int i = 0; i < 10; i++)
printf("%d ", a[i]);
}
int main()
{
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },t;
scanf("%d", &t);
f(a, t);
}
方法二:定义一个新数组,移动后的元素放在新定义的数组中,只需用单层循环,用空间换时间
#include<stdio.h> void f(int a[], int t) { int b[10] = { 0 }, i; for (i = 0; i < 10; i++) { if (i <=t) b[10-t+i] = a[i]; else b[i-t] = a[i]; } for (i = 0; i < 10; i++) printf("%d ", b[i]); } int main() { int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, t; scanf("%d", &t); f(a, t); }