Yêu cầu:
Viết chương trình nhập vào dãy số a gồm n số nguyên ( n <= 100 ).
• Hãy đảo ngược dãy đó.
Ví dụ: Nhập a: 3 4 5 2 0 4 1
Dãy sau khi đảo: 1 4 0 2 5 4 3
• (*)Hãy kiểm tra xem dãy đã cho có thứ tự chưa? (dãy được gọi là thứ tự khi là dãy tăng hoặc dãy giảm ).
Thuật toán:
Code:
/************************************************************ * Author: VNCODING * History * 2014/11/23 first create VNCODING *************************************************************/ #include "stdio.h" #include "conio.h" #include "string.h" #define INT_SIZE sizeof(int) #define ARR_MAX 100 void invert_arr(int A[], int n); bool is_order_arr(int A[], int n); void print_arr(int A[], int n, char name_arr); void main() { int A[] = {6, 5, -2, 3, 5, 4, 14, 11, 9, 16, 0, -1, 12}; int n = sizeof(A)/INT_SIZE; print_arr(A, n, 'A'); invert_arr(A, n); print_arr(A, n, 'B'); if(is_order_arr(A, n)) printf("\nArray A is order"); else printf("\nArray A isn't order"); getch(); } //Invert array void invert_arr(int A[], int n) { int i, j = n-1; int temp; for(i = 0; i < n/2; i++) { temp = A[i]; A[i] = A[j]; A[j] = temp; j--; } } //Check whether array is order or not? //Return: true: if to be order array //Return: false: otherwise bool is_order_arr(int A[], int n) { //bool asend_flg = false, descend_flg = false; int i; bool res = true; if(n < 2) { return false; } if(A[0] >= A[1]) { for(i = 1; i < n-1; i++) if(A[i] < A[i+1]) return false; } else { for(i = 1; i < n-1; i++) if(A[i] > A[i+1]) return false; } return true; } //Display array void print_arr(int A[], int n, char name_arr) { int i; printf("\n============================="); for(i = 0; i < n; i++) { printf("\n%c[%d] = %d", name_arr, i, A[i]); } }
Kết quả:
============================= A[0] = 6 A[1] = 5 A[2] = -2 A[3] = 3 A[4] = 5 A[5] = 4 A[6] = 14 A[7] = 11 A[8] = 9 A[9] = 16 A[10] = 0 A[11] = -1 A[12] = 12 ============================= B[0] = 12 B[1] = -1 B[2] = 0 B[3] = 16 B[4] = 9 B[5] = 11 B[6] = 14 B[7] = 4 B[8] = 5 B[9] = 3 B[10] = -2 B[11] = 5 B[12] = 6 Array A isn't order
Leave a Reply
You must be logged in to post a comment.