Display Multiplication Table in Go



In this tutorial, we will learn how to display the multiplication table of a given number in Go. We will cover the basic loop structure to generate and display the table.


What is a Multiplication Table

A multiplication table is a mathematical table used to define a multiplication operation for an algebraic system. It lists the results of multiplying a number by each of the whole numbers up to a specified limit.


Syntax

The syntax to display the multiplication table of a number in Go is:

func displayMultiplicationTable(n int) {
    for i := 1; i <= 10; i++ {
        fmt.Printf("%d x %d = %d\n", n, i, n*i)
    }
}


Example 1: Displaying the multiplication table of a number

We can use a for loop to generate and display the multiplication table of a given number.

For example,

  1. Define a function named displayMultiplicationTable that takes one parameter n of type int.
  2. Use a for loop to iterate through the numbers 1 to 10.
  3. In each iteration, multiply the number n by the current loop variable i and print the result in the format 'n x i = result'.
  4. In the main function, call the displayMultiplicationTable function with a sample number.

Go Program

package main

import (
    "fmt"
)

func displayMultiplicationTable(n int) {
    for i := 1; i <= 10; i++ {
        fmt.Printf("%d x %d = %d\n", n, i, n*i)
    }
}

func main() {
    // Display the multiplication table of 7
    displayMultiplicationTable(7)
}

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70