Sunday, January 25, 2015

Multiplication Table - Using FOR Loop in Go

FOR loop is a powerful construct and is frequently used in programming. You must understand it fully and feel at home while using it. 

Apart from this post you can practice this loop from the problems shared in the following examples:

1. FizzBuzz 
2. An interesting Go flag
2. for loop used in defer statement

Problem

Print Multiplication Table

Let us start

Suppose you wanted to print the multiplication table of a number say 2, in format like the following image:


Or may be like the following vertical format, the way we used to write in school:

Solution

To get the multiplication table of 2 you can simply write the following code snippet:

package main

import "fmt"

func main() {
 num := 2

 for j := 1; j <= 10; j++ {
  k := num * j
  fmt.Print(k)
  fmt.Printf("  ")
/*
//For a output in vertical format
fmt.Println(k) //Uncomment this line & comment above 2 lines
*/

 }
}

Play with the above code

The above code prints the multiplication table of 2. Change the value of variable num to get a multiplication table of a desired number.

The above code can be modified so that we can get multiplication tables up to a number defined by the user's input. The output could be like the following image:


The above output can be accomplished by the code shared in below image. Here we have used 2 FOR loops (also known nested FOR loop). The 2nd FOR loop is the same as you've seen in one of the above images captioned Simple FOR Loop. The second FOR loop has now become the inner loop and we have added one outer loop that takes care of the count of multiplication table up to a specific number - in this case I've entered 10 as you can see in the image just above this paragraph.


I am learning and sharing. To improve the code, feel free to share your experiences/tips in the comment section.

No comments:

Post a Comment