Yêu cầu:
– Xóa phần tử tại vị trí lẻ trong mảng.
Thuật toán:
– Giả sử xóa phần tử tại vị trí thứ i. Chúng ta thực hiện phép dồn các phần tử của mảng: A[i] = A[i+1].
Code:
/************************************************************ * Author: VNCODING * History * 2014/10/23 first create VNCODING *************************************************************/ #include <stdio.h> #include <conio.h> void delArr(float A[], int* n); void printArr(float A[], int n); void main() { float A[] = {-9, 2.3, 0, 5, 4.5, -2, 3, 8, 10}; int n = sizeof(A)/sizeof(float); printArr(A, n); delArr(A, &n); printArr(A, n); getch(); } void delArr(float A[], int* n) { int i, j; for(i = *n - 1; i >= 0; i--) { if(i%2 != 0) { for(j = i; j < *n-1; j++) { A[j] = A[j+1]; } (*n)--; } } } void printArr(float A[], int n) { int i; printf("\n---------------------------"); for(i = 0; i < n; i++) { printf("\nA[%d] = %.3f", i, A[i]); } printf("\n---------------------------"); }
Kết quả:
--------------------------- A[0] = -9.000 A[1] = 2.300 A[2] = 0.000 A[3] = 5.000 A[4] = 4.500 A[5] = -2.000 A[6] = 3.000 A[7] = 8.000 A[8] = 10.000 --------------------------- --------------------------- A[0] = -9.000 A[1] = 0.000 A[2] = 4.500 A[3] = 3.000 A[4] = 10.000 ---------------------------
Leave a Reply
You must be logged in to post a comment.