Printing a multiplication table is the simplest way to feel comfortable with a
for loop and formatted output. One loop, ten lines, and you are done.
Statement
Given a number n, print its multiplication table from n × 1 to n × 10.
Each line has the form n x i = result.
Constraints:
- Use a single
forloop that runsifrom1to10. - Format each line exactly as
n x i = result, with a space around each symbol. - Print one line per multiplier.
Example
For n = 3, the expected output is:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
Starter code
package main
import "fmt"
func main() {
n := 3
// Loop i from 1 to 10 and print "n x i = result".
}
Hints
Hint 1
A for i := 1; i <= 10; i++ loop gives you every multiplier from one to ten.
Hint 2
fmt.Printf lets you build the line with a format string. The verb %d prints
an integer.
Hint 3
Inside the loop, call fmt.Printf("%d x %d = %d\n", n, i, n*i). The \n moves
to the next line.
Solution
Show the solution
package main
import "fmt"
func main() {
n := 3
for i := 1; i <= 10; i++ {
fmt.Printf("%d x %d = %d\n", n, i, n*i)
}
}The loop runs i through the values 1 to 10. On each pass, fmt.Printf
fills the three %d placeholders with n, the current i, and the product
n*i, then the \n escape ends the line. Ten iterations produce the ten rows
of the table.
Common mistakes:
- Using
fmt.Printlnwith string concatenation, which is harder to read and easy to get wrong.Printfwith%dis clearer. - Forgetting the
\nin the format string, so every result lands on one line. - Starting the loop at
0, which adds an unwantedn x 0 = 0row.
The for loop is the only loop Go has, and it does a lot. Master it in
Loops in Go.