Goland Program to Read a Number (n) And Print the Series "1+2+…..+n= "

Go ProgrammingServer Side ProgrammingProgramming

Steps

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

Explanation

  • User must first enter the value and store it in a variable, n.
  • The for loop enables i to range between 1 and n (as n+1 is not included).
  • For each iteration, the value of i is printed.
  • '+' operator is printed only if i

Example

 Live Demo

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

Output

Enter the number: 10
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
raja
Published on 31-Jul-2021 15:04:23
Advertisements