행렬은 행과 열의 형태로 배열된 직사각형 숫자 배열입니다.
행렬의 예는 다음과 같습니다.
4*3 행렬은 아래와 같이 4개의 행과 3개의 열을 가지고 있습니다. -
3 5 1 7 1 9 3 9 4 1 6 7
다차원 배열을 사용하여 두 개의 행렬을 더하는 프로그램은 다음과 같습니다.
예시
#include <iostream>
using namespace std;
int main() {
int r=2, c=4, sum[2][4], i, j;
int a[2][4] = {{1,5,9,4} , {3,2,8,3}};
int b[2][4] = {{6,3,8,2} , {1,5,2,9}};
cout<<"The first matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(i=0;i<r;++i)
for(j=0;j<c;++j)
sum[i][j]=a[i][j]+b[i][j];
cout<<"Sum of the two matrices is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<sum[i][j]<<" ";
cout<<endl;
}
return 0;
} 출력
The first matrix is: 1 5 9 4 3 2 8 3 The second matrix is: 6 3 8 2 1 5 2 9 Sum of the two matrices is: 7 8 17 6 4 7 10 12
위의 프로그램에서 먼저 두 개의 행렬과 b가 정의됩니다. 이것은 다음과 같이 표시됩니다.
int a[2][4] = {{1,5,9,4} , {3,2,8,3}};
int b[2][4] = {{6,3,8,2} , {1,5,2,9}};
cout<<"The first matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
} 두 개의 행렬은 중첩 for 루프를 사용하여 추가되고 결과는 행렬 sum[][]에 저장됩니다. 이것은 다음 코드 스니펫에 나와 있습니다.
for(i=0;i<r;++i) for(j=0;j<c;++j) sum[i][j]=a[i][j]+b[i][j];
두 행렬의 합을 구한 후 화면에 인쇄합니다. 이것은 다음과 같이 수행됩니다 -
cout<<"Sum of the two matrices is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<sum[i][j]<<" ";
cout<<endl;
}