设计一个函数:将一维整型数组中的元素逆序存放。比如本来是1,3,4,2,逆序存放就变成了:2,4,3,1。两种循环方式。
#include <stdio.h>
void reverse(int array[],int length);
void reverse2(int array[],int length);
int main(int argc, const char * argv[]) {
int ages[] = {10,11,12,13,14,15};
//reverse(ages,sizeof(ages)/4);
reverse2(ages,sizeof(ages)/4);
for (int i=0;i<6;i++)
{
printf("ages[%d]=%d\n",i,ages);
}
//ages[0] ages[5] ages ages[length--1]
//ages[1] ages[4]
//ages[2] ages[3]
return 0;
}
void reverse(int array[],int length)
{
int left = 0;
int right = length-1;
while (left<right)
{
int temp = array[left];
array[left] = array[right];
array[right] = temp;
left++;
right--;
}
}
void reverse2(int array[],int length)
{
int right = length-1;
for (int left=0;left<right;left++,right--)
{
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}
|
|