Two positive integers n and m are given. Print the matrix that
consists of n lines and m columns, filled with positive integers
from 1 to n * m, as shown in the sample.
Input. Two positive integers n and
m (1 ≤ n, m
≤ 100).
Output. Print the required matrix.
Sample input |
Sample output |
2 3 |
1 2 3 4 5 6 |
array
The
problem can be solved using a double loop. Print the matrix on the fly.
The
problem can be solved using a two dimensional
array. Generate and store the matrix in the two dimensional
array. Print the
elements of the array as required.
Read the input data.
scanf("%d %d", &n,
&m);
In the variable cnt iterate over the positive integers from 1 to n * m.
Print the required matrix.
cnt = 1;
for (i = 0; i < n; i++)
{
for (j = 0; j <
m; j++)
printf("%d
", cnt++);
printf("\n");
}
#include <stdio.h>
int n, m, i, j, cnt;
int a[100][100];
int main(void)
{
scanf("%d
%d", &n, &m);
cnt = 1;
for (i = 0; i <
n; i++)
for (j = 0; j <
m; j++)
a[i][j] = cnt++;
for (i = 0; i <
n; i++)
{
for (j = 0; j <
m; j++)
printf("%d
", a[i][j]);
printf("\n");
}
return 0;
}
Java realization
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new
Scanner(System.in);
int n = con.nextInt();
int m = con.nextInt();
int a[][] = new int[n+1][m+1];
int cnt = 1;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
a[i][j] = cnt++;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
System.out.print(a[i][j] + " ");
System.out.println();
}
con.close();
}
}
Python realization
n, m = map(int,input().split())
cnt = 1
for i in range(n):
for j in range(m):
print(cnt, end = ' ')
cnt += 1
print()