8545. Multiplication table

 

Print multiplication table n * n with alignment.

 

Input. One integer n (1 ≤ n ≤ 9).

 

Output. Print multiplication table n * n with alignment as shown in sample.

 

Sample input

Sample output

5

1  2  3  4  5

2  4  6  8 10

3  6  9 12 15

4  8 12 16 20

5 10 15 20 25

 

 

SOLUTION

loops

 

Algorithm analysis

Use a double loop to print the multiplication table.

 

Algorithm realization

Read the input value n.

 

scanf("%d",&n);

 

Using a double loop, print the multiplication table. For alignment, each number should be printed in two positions, use the format %2d.

 

for (i = 1; i <= n; i++)

{

  for (j = 1; j <= n; j++)

    printf("%2d ", i * j);

  printf("\n");

}

 

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[][] = new int[n+1][n+1];

 

    for(int i = 1; i <= n; i++)

    for(int j = 1; j <= n; j++)

      m[i][j] = i * j;

 

    for(int i = 1; i <= n; i++)

    {

      for(int j = 1; j <= n; j++)

        System.out.printf("%2d ", m[i][j]);

      System.out.println();

    }

    con.close();

  }

}

 

Python realization

 

n = int(input())

 

for x in range(1, n+1):

  for y in range(1, n+1):

    print(str(x*y).rjust(2), end = ' ')

  print()