Yêu cầu:
– Tính tổng các phần tử cực đại trong mảng các số nguyên (phần tử cực đại là phần tử lớn hơn các phần tử xung quanh nó).
Ví dụ: 1 5 2 6 3 5 1 8 6 (5, 6, 5, 8 là các phần tử cực đại)
Thuật toán:
Code:
/************************************************************ * Author: VNCODING * History * 2014/10/05 first create VNCODING *************************************************************/ #include "stdio.h" #include "conio.h" #define LEN_MAX 100 // do dai toi da cua mang int sum_of_max(int A[], int len); void main() { int arr[LEN_MAX]; int n; int i; do { printf("\nNhap kich thuoc mang: "); scanf("%d", &n); } while (n > LEN_MAX || n <= 0); for (i = 0; i < n;i++) { printf("\nA[%d] = ", i); scanf("%d", &arr[i]); } printf("\nTong cac phan tu max: %d", sum_of_max(arr, n)); getch(); } int sum_of_max(int A[], int len) { int i; int sum = 0; for (i = 0; i <= len - 3; i++) if(A[i+1] > A[i] && A[i+1] > A[i+2]) sum += A[i+1]; return sum; }
Kết quả:
Nhap kich thuoc mang: 7 A[0] = 1 A[1] = 2 A[2] = 3 A[3] = 2 A[4] = 9 A[5] = 0 A[6] = 3 Tong cac phan tu max: 12
Leave a Reply
You must be logged in to post a comment.