Golang Program to Print an Inverted Star Pattern

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 n-1 and 0 with a decrement of 1 with each iteration.
  • Multiply the empty spaces with n-i and '*' with i and print both of them.
  • Exit.

Explanation

  • User must first enter the value and store it in a variable, n.
  • The for loop enables i to range between n-1 and 0 with a decrement of 1 with each iteration.
  • For each iteration, " " is multiplied with n-i and '*' is multiplied with i to ensure correct spacing of the stars.
  • The required pattern is printed.

Example

 Live Demo

package main
import "fmt"
func main(){
   var n int
   fmt.Print("Enter a number: ")
   fmt.Scanf("%d", &n)
   for i:=0; i<=n; i++{
      for j:=0; j<n-i; j++{
         fmt.Printf(" ")
      }
      for k:=0; k<i; k++{
      fmt.Printf("*")
   }
   fmt.Println()
}
}

Output

Enter a number: 6
     *
    **
   ***
  ****
 *****
******
raja
Published on 31-Jul-2021 15:15:35
Advertisements