Ví dụ mảng 2 chiều trong C/C++

Từ khóa


/*
Vi du 1 [ mang 2 chieu ]
 - Nhap vao tu ban phim ma tran vuong chua cac so nguyen co kich thuoc n (3<=n<=8)
 - In ma tran vua nhap
 - Dem so chan trong ma tran
 - Tinh tong theo dong cua ma tran

 - Tim so lon nhat, nho nhat tron ma tran
 - In ra vi tri xuat hien cac so nguyen to trong ma tran


*/
#include<iostream>
#include<conio.h>
using namespace std;
int
a[8][8],n;

void
Nhap(){
do
{
cout<<"\n n= ";
cin>>n;
if
(n<3||n>8)
cout<<"\n Nhap lai n!";
}
while(n<3||n>8);
// Nhap ma tran
cout<<"\n Nhap ma tran: ";
for
(int i=0;i<n;i++)
for
(int j=0;j<n;j++) {
cout<<"\n a["<<i<<"]["<<j<<"]= ";
cin>>a[i][j];
}
}

// In ma tran
void InMaTran(){
cout<<"\n IN MA TRAN VUA NHAP: \n";
for
(int i=0;i<n;i++) {
for
(int j=0;j<n;j++)
cout<<a[i][j]<<"\t";
cout<<"\n";
}
}

// Dem so phan tu chan trong ma tran
int DemSoChan(){
int
d=0;
for
(int i=0;i<n;i++)
for
(int j=0;j<n;j++)
if
(a[i][j]%2==0)
d++;
return
d;
}

// Tinh tong dong
void TongDong(){
cout<<"\n Tong theo dong cua ma tran: \n";
int
s;
for
(int i=0;i<n;i++){
s=0;
for
(int j=0;j<n;j++)
s=s+a[i][j];
cout<<"\n Tong dong "<<i<<" : "<<s;
}
}

// Ham kiem tra so nguyen to
int TestSoNT(int a){
for
(int i=2;i<a;i++)
if
(a%i==0)
return
0;
return
1;
}

// In ra vi tri so nguyen to
void ViTriSoNT(){
cout<<"\n VI TRI CAC SO NGUYEN TO TRONG MA TRAN: \n";
for
(int i=0;i<n;i++)
for
(int j=0;j<n;j++)
if
(TestSoNT(a[i][j])==1)
cout<<"["<<i<<"]["<<j<<"] ;";
}

// ham chinh
int main(){

Nhap();
InMaTran();
cout<<"\n So so chan trong ma tran: "<<DemSoChan();
TongDong();
ViTriSoNT();
return
0;
}

Bài liên quan

Bài liên quan