Yêu cầu:
Viết chương trình tính tổng tất cả các phần tử xung quanh trên mảng các số nguyên. (Phần tử xung quanh là hai phần tử bên cạnh cộng lai bằng chính nó (Ví dụ: 1 3 2 → 1,2 là hai phần tử xung quanh của 3).
Ví dụ: 1 3 2 5 3 9 6 → tổng 17
Thuật toán:
Code:
/************************************************************ * Author: VNCODING * History * 2014/11/16 first create VNCODING *************************************************************/ #include "stdio.h" #include "conio.h" int sum_around_elmnt(int A[], int n); void main( void ) { int A[] = {1, 3, 2, 4, 2, 3, 1, 5, 4, 0, 5, 6}; int n = sizeof(A)/sizeof(int); printf("\nsum of around elements is %d", sum_around_elmnt(A, n)); getch(); } //Calculate sum of around elements int sum_around_elmnt(int A[], int n) { int i; int sum = 0; for(i = 1;i < n - 1;i++) { if(A[i] == (A[i-1] + A[i+1])) sum += A[i]; } return sum; }
Kết quả:
sum of around elements is 15
Leave a Reply
You must be logged in to post a comment.