In this tutorial, we will learn how to generate a dynamic multiplication table based on user input in Go. You’ll get hands-on experience with loops, conditions, and user input in Go.
A multiplication table is a set of results showing how one number (the multiplier) interacts with other numbers (the multiplicands). For example, the multiplication table for 5 looks like this:
5 x 1 | = 5 |
5 x 2 | = 10 |
5 x 3 | = 15 |
5 x 4 | = 20 |
5 x 5 | = 25 |
5 x 6 | = 30 |
5 x 7 | = 35 |
5 x 8 | = 40 |
5 x 9 | = 45 |
5 x 10 | = 50 |
In this exercise, we will build a program where the user can input any number, and the program will generate the multiplication table for that number.
To create a dynamic multiplication table in Go, we need to :
We will use a for loop to repeat an action multiple times. In this case, we repeat the multiplication for numbers 1 through 10.
for i := 1; i <= 10; i++ { // Multiply and print }
fmt.Scanln()
function, which reads the user’s input and stores it in a variable.Let’s break down how we’ll structure the program :
Writing the Code :
Now that we have the plan, we can write the code. We’ll :
for
loop to generate results for numbers 1 to 10.package main
import "fmt"
// Function to generate the multiplication table
func multiplicationTable(number int) {
fmt.Printf("Multiplication Table for %d:\n", number)
for i := 1; i <= 10; i++ { // Looping from 1 to 10
fmt.Printf("%d x %d = %d\n", number, i, number*i)
}
}
func main() {
var number int
// Ask the user for a number to generate the multiplication table
fmt.Print("Enter a number to generate the multiplication table: ")
fmt.Scanln(&number)
// Check if the number is positive
if number <= 0 {
fmt.Println("Please enter a positive number.")
} else {
multiplicationTable(number) // Generate and display the table
}
}
🚀 Thank you for reading these articles! If you find this content valuable and want to support my work, a coffee would be greatly appreciated! ☕😊
💻 I am a freelance web developer, and I personally create and maintain this website. Any support would help me improve and expand it further! 🙌