If I have an array, let's say [1,2,3,4,5,6], how can I make it to be [2,3,4,5,6,1]? Which loop should I use for this? I tried using a for loop, however since I am fairly new to C programming I was unable to produce the output.
如果我有一个数组,让我们说[1,2,3,4,5,6],我怎么能让它成为[2,3,4,5,6,1]?我应该使用哪个循环?我尝试使用for循环,但由于我对C编程很新,我无法生成输出。
3 个解决方案
#1
1
int array[6] = { 1, 2, 3, 4, 5, 6 };
int array_size = 6;
// array is now { 1, 2, 3, 4, 5, 6 }
int array = array[0]; // #1
for(int i = 1; i < array_size; i++) { // #2
array[i - 1] = array[i];
}
array[array_size - 1] = tmp; // #3
// array is now { 2, 3, 4, 5, 6, 1 }
It works like this:
它的工作原理如下:
- Take the first value and store it in a special variable,
tmp
. - Take each of the remainding values and move one step to the front of the array.
- Take the value stored in
tmp
and move it to the back of the array.
取第一个值并将其存储在一个特殊变量tmp中。
获取每个剩余值并将一步移动到数组的前面。
获取存储在tmp中的值并将其移动到数组的后面。
#2
0
Whoops. I misread the problem the first time
哎呦。我第一次误解了这个问题
int len = 5;
char *pOriginal = {0,1,2,3,4}
char ch0 = pOrigina[0];
memmove(pOriginal, &pOrigina[1], len-2) // Thanks guys!
pOriginal[len-1] = ch0;
#3
-1
If you know the size of the array then you can use swapping, Just save the first variable in a temporary variable and then do a swapping of i element with the i+1 element and then at the last position do the swapping between last element and temporary variable. thank you...
如果您知道数组的大小,那么您可以使用交换,只需将第一个变量保存在临时变量中,然后用i + 1元素交换i元素,然后在最后一个位置进行最后一个元素之间的交换。临时变量。谢谢...
#1
1
int array[6] = { 1, 2, 3, 4, 5, 6 };
int array_size = 6;
// array is now { 1, 2, 3, 4, 5, 6 }
int array = array[0]; // #1
for(int i = 1; i < array_size; i++) { // #2
array[i - 1] = array[i];
}
array[array_size - 1] = tmp; // #3
// array is now { 2, 3, 4, 5, 6, 1 }
It works like this:
它的工作原理如下:
- Take the first value and store it in a special variable,
tmp
. - Take each of the remainding values and move one step to the front of the array.
- Take the value stored in
tmp
and move it to the back of the array.
取第一个值并将其存储在一个特殊变量tmp中。
获取每个剩余值并将一步移动到数组的前面。
获取存储在tmp中的值并将其移动到数组的后面。
#2
0
Whoops. I misread the problem the first time
哎呦。我第一次误解了这个问题
int len = 5;
char *pOriginal = {0,1,2,3,4}
char ch0 = pOrigina[0];
memmove(pOriginal, &pOrigina[1], len-2) // Thanks guys!
pOriginal[len-1] = ch0;
#3
-1
If you know the size of the array then you can use swapping, Just save the first variable in a temporary variable and then do a swapping of i element with the i+1 element and then at the last position do the swapping between last element and temporary variable. thank you...
如果您知道数组的大小,那么您可以使用交换,只需将第一个变量保存在临时变量中,然后用i + 1元素交换i元素,然后在最后一个位置进行最后一个元素之间的交换。临时变量。谢谢...