Various function operations on arrays
Create an array,
Implement init() to initialize array
Empty() is implemented to empty the array
Implement the reverse() function to complete the inversion of array elements.
Requirements: design the parameters of the function and return the value.
1. Implement the init() function to initialize the array.
The code is as follows:
void Init(int arr[], int len) { printf("Please input%d Number initialization array:", len); int i = 0; for ( ; i < len; i++) { scanf("%d", &arr[i]); } printf("The initialized array is:\n"); for ( i = 0; i < len; i++) { printf("%d ", arr[i]); } printf("\n"); }
2. Implement the reverse() function to complete the inversion of array elements.
Method 1:
Define a new array arr2 [], assign all the data in arr [] to arr2 []; assign the data in arr2 [] to arr [] from the back to the front;
The code is as follows:
void Reverse(int arr[], int len) { int i = 0; int tmp = 0; int arr2[10]; printf("The array after inversion is:\n"); for (i = 0; i<len; i++) { arr2[i] = arr[i]; } for (i = 0; i<len; i++) { arr[i] = arr2[len - 1 - i]; } for (i = 0; i < len; i++) { printf("%d ", arr[i]); } printf("\n"); }
Method two:
The most common way of thinking is to exchange array elements in pairs from front to back and from back to front through intermediate variables;
The code is as follows:
int Reverse(int arr[], int len) { int i = 0; int tmp = 0; printf("The array after inversion is:\n"); for (i = 0; i <= (len / 2); i++) { tmp = arr[i]; arr[i] = arr[len - i - 1]; arr[len - i - 1] = tmp; } for (i = 0; i < len; i++) { printf("%d ", arr[i]); } printf("\n"); }
Method three:
Method 2 is optimized. When two elements are exchanged, intermediate variables are no longer introduced and XOR method is used.
XOR truth table:
The code is as follows:
int Reverse(int arr[], int len) { int i = 0; int tmp = 0; printf("The array after inversion is:\n"); for (i = 0; i <= (len / 2); i++) { arr[i] ^= arr[len - i - 1]; arr[len - i - 1] ^= arr[i]; arr[i] ^= arr[len - i - 1]; } for (i = 0; i < len; i++) { printf("%d ", arr[i]); } printf("\n"); }
3. Empty() is implemented to empty the array.
The code is as follows:
int Empty(int arr[], int len) { int i = 0; printf("The empty array is:\n"); for (i = 1; i <= len; i++) { arr[i] = 0; printf("%d ", arr[i]); } }
4. The main function calls to realize the function.
Head file:
#include <stdio.h>
The code is as follows:
int main() { int a[10]; int len = 0; len = sizeof(a) / sizeof(a[0]); Init(a, len); Reverse(a, len); Empty(a, len); system("pause"); return 0; }