Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

C 언어로 두 행렬이 같은지 비교하는 프로그램 완벽 정리

이 프로그램에서는 사용자로부터 두 행렬의 차수(행과 열의 개수)와 각 행렬의 원소를 입력받은 후, 두 행렬을 서로 비교합니다.

비교 결과는 다음 세 가지 경우로 나뉩니다.

  • 두 행렬의 크기와 모든 원소가 모두 같으면 “두 행렬이 같다”고 출력합니다.
  • 크기는 같지만 원소가 하나라도 다르면 “비교는 가능하지만 두 행렬은 같지 않다”고 출력합니다.
  • 크기 자체가 다르면 “두 행렬을 비교할 수 없다”고 출력합니다.

프로그램 코드

다음은 두 행렬이 같은지 비교하는 C 프로그램입니다 −

#include <stdio.h>
#include <conio.h>
main(){
    int A[10][10], B[10][10];
    int i, j, R1, C1, R2, C2, flag =1;
    printf("Enter the order of the matrix A\n");
    scanf("%d %d", &R1, &C1);
    printf("Enter the order of the matrix B\n");
    scanf("%d %d", &R2,&C2);
    printf("Enter the elements of matrix A\n");
    for(i=0; i<R1; i++){
        for(j=0; j<C1; j++){
            scanf("%d",&A[i][j]);
        }
    }
    printf("Enter the elements of matrix B\n");
    for(i=0; i<R2; i++){
        for(j=0; j<C2; j++){
            scanf("%d",&B[i][j]);
        }
    }
    printf("MATRIX A is\n");
    for(i=0; i<R1; i++){
        for(j=0; j<C1; j++){
            printf("%3d",A[i][j]);
        }
        printf("\n");
    }
    printf("MATRIX B is\n");
    for(i=0; i<R2; i++){
        for(j=0; j<C2; j++){
            printf("%3d",B[i][j]);
        }
        printf("\n");
    }
    /* 두 행렬의 동일 여부 비교 */
    if(R1 == R2 && C1 == C2){
        printf("Matrices can be compared\n");
        for(i=0; i<R1; i++){
            for(j=0; j<C2; j++){
                if(A[i][j] != B[i][j]){
                    flag = 0;
                    break;
                }
            }
        }
    }
    else{
        printf(" Cannot be compared\n");
        exit(1);
    }
    if(flag == 1 )
        printf("Two matrices are equal\n");
    else
    printf("But,two matrices are not equal\n");
}

코드 동작 원리

  1. 먼저 R1, C1R2, C2에 각각 행렬 A와 B의 행·열 개수를 입력받습니다.
  2. 이중 반복문(for)으로 두 행렬의 원소를 순서대로 입력받습니다.
  3. 입력된 행렬 A와 B를 화면에 출력하여 사용자가 확인할 수 있도록 합니다.
  4. 두 행렬의 크기가 같은지 먼저 검사하고, 크기가 같으면 모든 위치의 원소를 하나씩 비교합니다. 이때 원소가 다르면 flag를 0으로 설정하고 반복문을 종료합니다.
  5. 마지막으로 flag 값에 따라 두 행렬이 같은지 여부를 판단하여 출력합니다.

실행 결과

위 프로그램을 실행하면 다음과 같은 결과를 확인할 수 있습니다 −

Run 1:
Enter the order of the matrix A
2 2
Enter the order of the matrix B
2 2
Enter the elements of matrix A
1
2
3
4
Enter the elements of matrix B
1
2
3
4
MATRIX A is
   1 2
   3 4
MATRIX B is
   1 2
   3 4
Matrices can be compared
Two matrices are equal

Run 2:
Enter the order of the matrix A
2 2
Enter the order of the matrix B
2 2
Enter the elements of matrix A
1
2
3
4
Enter the elements of matrix B
5
6
7
8
MATRIX A is
   1 2
   3 4
MATRIX B is
   5 6
   7 8
Matrices can be compared
But,two matrices are not equal

첫 번째 실행에서는 두 행렬의 크기와 원소가 모두 일치하므로 “Two matrices are equal(두 행렬이 같습니다)”이 출력되고, 두 번째 실행에서는 크기는 같지만 원소가 다르므로 “two matrices are not equal(두 행렬이 같지 않습니다)”이 출력됩니다. 만약 두 행렬의 행 또는 열의 개수가 달랐다면 “Cannot be compared(비교할 수 없습니다)”가 출력되며 프로그램이 종료됩니다.