Tổng các phần tử trên đường chéo phụ

toi1em

Member
Feb 20, 2012
949
0
16
40
320x50.jpg


Bài toán: Tổng các phần tử trên đường chéo phụ

Input: ma trận a có n dòng, n cột

Xử lý: gán sum=0

duyệt mảng và tính tổng các phần tử trên đường chéo phụ

Ví dụ: a[4][4]={(12,23,15,43)

(4,8,32,22)

(21,34,6,5)

(11,7,20,12)}

Sum=a[3][0]+a[2][1]+a[1][2]+a[0][3]=11+34+32+43=120

Tổng quát

Sum=sum+a[n-1-i]

Output: sum

Hàm tính tổng


double tong(int a[][MAX], int n) { double sum=0; for(int i=0;i<n;i++) sum=sum+a[n-1-i]; return sum; }



1

2

3

4

5

6

7


double tong(int a[][MAX], int n)

{

double sum=0;

for(int i=0;i<n;i++)

sum=sum+a[n-1-i];

return sum;

}




Chương trình


#include<conio.h> #include<stdio.h> #include<math.h> #define MAX 100 void nhapmatran(int a[][MAX], int &n); void xuatmatran(int a[][MAX], int n); double tong(int a[][MAX], int n); void main() { int a[MAX][MAX],n; nhapmatran(a,n); printf("\nNoi dung cua ma tran\n"); xuatmatran(a,n); double kq=tong(a,n); printf("\nTong cac phan tu tren duong cheo phu la %8.2f",kq); getch(); } void nhapmatran(int a[][MAX], int &n) { do { printf("\nNhap n: "); scanf("%d",&n); }while(n<=0 || n>100); for(int i=0;i<n;i++) for(int j=0;j<n;j++) { printf("\nSo phan tu a[%d][%d] la: ",i,j); scanf("%d",&a[j]); } } void xuatmatran(int a[][MAX], int n) { for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { printf("%5d",a[j]); } printf("\n"); } } double tong(int a[][MAX], int n) { double sum=0; for(int i=0;i<n;i++) sum=sum+a[n-1-i]; return sum; }



1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49


#include<conio.h>

#include<stdio.h>

#include<math.h>

#define MAX 100

void nhapmatran(int a[][MAX], int &n);

void xuatmatran(int a[][MAX], int n);

double tong(int a[][MAX], int n);

void main()

{

int a[MAX][MAX],n;

nhapmatran(a,n);

printf("\nNoi dung cua ma tran\n");

xuatmatran(a,n);

double kq=tong(a,n);

printf("\nTong cac phan tu tren duong cheo phu la %8.2f",kq);

getch();

}

void nhapmatran(int a[][MAX], int &n)

{

do

{

printf("\nNhap n: ");

scanf("%d",&n);

}while(n<=0 || n>100);

for(int i=0;i<n;i++)

for(int j=0;j<n;j++)

{

printf("\nSo phan tu a[%d][%d] la: ",i,j);

scanf("%d",&a[j]);

}

}

void xuatmatran(int a[][MAX], int n)

{

for(int i=0;i<n;i++)

{

for(int j=0;j<n;j++)

{

printf("%5d",a[j]);

}

printf("\n");

}

}

double tong(int a[][MAX], int n)

{

double sum=0;

for(int i=0;i<n;i++)

sum=sum+a[n-1-i];

return sum;

}




Mình chia sẽ code này đê các bạn tham khảo các vấn đề tương tự. Tuy nhiên các bạn nên tự làm lại, đừng nên copy. Nếu gặp vấn đề gì khó khăn, hoặc thắc mắc gì, các bạn có thể đặt câu hỏi ở cuối bài. Mình sẽ giải đáp.

Chúc các bạn thành công!

Sưu tầm & Tổng hợp
w: www.hanoiyeu.com
e: [email protected]