This blog is under construction

Wednesday, 24 July 2013

C program to copy one matrix to another

Write a C program to copy one matrix to another.


  #include <stdio.h>
  #define MAXROW 10
  #define MAXCOL 10

  int main() {
        int mat1[MAXROW][MAXCOL], mat2[MAXROW][MAXCOL];
        int i, j, n, row, col;

        /* get the number of rows from the user */
        printf("Enter the number of rows(0-10):");
        scanf("%d", &row);

        /* get the number of columns from the user */
        printf("Enter the number of columns(0-10):");
        scanf("%d", &col);

        /* boundary check */
        if (row > MAXROW || col > MAXCOL || row < 0 || col < 0) {
                printf("Boundary Level Exceeded!!\n");
                return 0;
        }

        /* get the entries for the input matrix */
        printf("Enter your entries for the input matrix:\n");
        for (i = 0; i < row; i++) {
                for (j = 0; j < col; j++) {
                        scanf("%d", &mat1[i][j]);
                }
        }

        /* copy the contents in input matrix to output matrix */
        for (i = 0; i < row; i++) {
                for (j = 0; j < col; j++) {
                        mat2[i][j] = mat1[i][j];
                }
        }

        /* print the contents in the output matrix */
        printf("Contents in the output matrix:\n");
        for (i = 0; i < row; i++) {
                for (j = 0; j < col; j++) {
                        printf("%d ", mat1[i][j]);
                }
                printf("\n");
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of rows(0-10):3
  Enter the number of columns(0-10):3
  Enter your entries for the input matrix:
  10 20 30
  40 50 60
  70 80 90
  Contents in the output matrix:
  10 20 30 
  40 50 60   
  70 80 90 


No comments:

Post a Comment