Bondhu

mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.8 kB
5
Indexable
Never
/*
 * Write a program in any language to find the sum of rows and columns of a m x n matrix, 
 * where m and n is taken input from the user. Give the output in the following format
 * input 
 * 4 * 3 matrix 
 * 1 2 3 4
 * 5 6 7 8
 * 9 0 1 2
 *
 * output
 * 1 2 3 4   | 10
 * 5 6 7 8   | 26
 * 9 0 1 2   | 12
 * ----------|-----
 * 15 8 11 14|
 * */

#include <stdio.h>
#include <string.h>

int main() {
  // Initializing row and column count;
  int row = 0, col = 0;
  // Taking row and column input;
  scanf("%d %d", &row, &col);
  printf("Number of rows and columns: %d %d\n", row, col);
  // From example, we saw, there will be an extra row and an extra column;
  // That's why decalring an m+1 * n+1 matrix
  // this will make calculation easier
  int matrix[row+1][col+1];
  // Setting all of the entries of matrix to 0, mainly needed for result
  memset(matrix, 0, sizeof(matrix));
  // Essential variable for loop
  int i,j;
  // Initial state of our matrix
  printf("Matrix initial\n");
  for (i=0;i<row + 1;i++) {
    for (j=0;j<col + 1;j++) {
      printf("%d ", matrix[i][j]);
    }
    printf("\n");
  }
  // While we are taking input, we are also adding current number to row result mat[currentRow][column] entry. 
  // We are also adding current number to column result entry matrix[row][currentColumn]
  // If we do this way, then we don't need to do another O(n^2) loop
  for (i=0;i<row;i++) {
    for (j=0;j<col;j++) {
      scanf("%d", &matrix[i][j]);
      matrix[i][col] += matrix[i][j];
      matrix[row][j] += matrix[i][j];
    }
  }
  printf("Matrix after input\n");
  for (i=0;i<row + 1;i++) {
    for (j=0;j<col + 1;j++) {
      // Skipping last entry
      if (i == row && j == col) continue;
      printf("%d ", matrix[i][j]);
    }
    printf("\n");
  }
  return 0;
}
Leave a Comment