练习题2.11
1 /* 2 CSAPP练习题2.11,并做了一些扩展 3 指定或者用户输入一个数组(100以内),打印反转前后的所有数组元素 4 */ 5 #include <stdio.h> 6 7 void inplace_swap(int *x, int *y); //互换值 8 void reverse_array(int a[], int cnt); //数组反转 9 void print_array(int a[], int length); //数组打印,数组长度也需传入 10 11 int main() { 12 //输入一个数组并打印反转前后的数组元素 13 int i, n; 14 int arr[100]; //数组长度上限位100 15 printf("请输入数组长度(100以内):\n"); 16 scanf("%d", &n); 17 for (i = 0; i < n; i++) { 18 scanf("%d", &arr[i]); 19 } 20 //反转前 21 printf("反转前:\n"); 22 printf("arr[]="); 23 print_array(arr, n); 24 //反转 25 reverse_array(arr, n); 26 //反转后 27 printf("反转后:\n"); 28 printf("arr[]="); 29 print_array(arr, n); 30 return 0; 31 } 32 //互换元素 33 void inplace_swap(int *x, int *y) { 34 *x = *x ^ *y; 35 *y = *x ^ *y; 36 *x = *x ^ *y; 37 } 38 //数组反转 39 void reverse_array(int a[], int cnt) { 40 int first, last; 41 for (first = 0, last = cnt - 1; first < last; first++, last--) { 42 inplace_swap(&a[first], &a[last]); 43 } 44 } 45 //数组打印 46 void print_array(int a[], int length) { 47 printf("{"); 48 for (int i = 0; i < length; i++) { 49 printf("%d", a[i]); 50 if (i < length - 1) 51 printf(","); 52 } 53 printf("}\n"); 54 }
标签:练习题,CSAPP,int,反转,arr,数组,printf,array,2.11 From: https://www.cnblogs.com/leon0408/p/17301402.html