Golang Program to Read a Number (n) and Print the Natural Numbers Summation Pattern

Go ProgrammingServer Side ProgrammingProgramming

Let's suppose the number is: 4

Then, the Summation Patten would be:

1 = 1

1 + 2 = 3

1 + 2 + 3 = 6

1 + 2 + 3 + 4 = 10

Steps

  • Take a value from the user and store it in a variable, n.
  • Use two for loops where the value of t ranges between the values of 1 and n and the value of i ranges between 1 and t.
  • Print the value of i and '+' operator.
  • Find the sum of elements in the list.
  • Print '=' followed by the total sum.
  • Exit.

Example

 Live Demo

package main
import "fmt"
func main(){
   var n int
   fmt.Print("Enter number: ")
   fmt.Scanf("%d", &n)
   for t:=1; t<=n; t++{
      sum := 0
      for i:=1; i<=t; i++{
         fmt.Printf("%d ", i)
         if i < t{
            fmt.Printf("+ ")
         }
         sum += i
      }
      fmt.Printf("= %d\n", sum)
   }
}

Output

Enter number: 6
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
raja
Published on 31-Jul-2021 15:05:26
Advertisements