Print Matrix#8530

Print Matrix (Editorial)

Read the input matrix into a two-dimensional array. Then print the submatrix of size [1 .. r] \times [1 .. c].

Algorithm implementation

Declare a two-dimensional array.

int m[101][101];

Read the input matrix n \times n.

scanf("%d", &n);
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
  scanf("%d", &m[i][j]);

Read the values of and .

scanf("%d %d", &r, &c);

Print the r \times c submatrix.

for (i = 1; i <= r; i++)
{
  for (j = 1; j <= c; j++)
    printf("%d ", m[i][j]);
  printf("\n");
}

Java implementation

import java.util.*;
 
public class Main
{
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    int n = con.nextInt();
    int m[][] = new int[n][n];
    for(int i = 0; i < n; i++)
    for(int j = 0; j < n; j++)
      m[i][j] = con.nextInt();
    
    int r = con.nextInt();
    int c = con.nextInt();

    for(int i = 0; i < r; i++)
    {
      for(int j = 0; j < c; j++)
        System.out.print(m[i][j] + " ");
      System.out.println();
    }
    con.close();
  }
}

Python implementation

Read the input data.

n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
r, c = map(int, input().split())

Print the r \times c submatrix.

for i in range(r):
  for j in range(c):
    print(a[i][j],end = " ")
  print()

Python implementation — submatrix

Read the input data.

n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
r, c = map(int, input().split())

Extract the r \times c submatrix from matrix .

res = [row[:c] for row in a[:r]]

Print the r \times c submatrix.

for row in res:
  print(*row)