Go Program to Print Pascal Triangle

Write a Go program to print the pascal triangle number pattern using for loop.

package main

import (
	"fmt"
	"strconv"
)

func main() {

	var i, j, row, number int

	fmt.Print("Enter Pascals Number Triangle Pattern Rows = ")
	fmt.Scanln(&row)

	fmt.Println("**** Pascals Number Triangle Pattern ****")

	for i = 0; i < row; i++ {
		number = 1
		fmt.Printf("%"+strconv.Itoa((row-i)*2)+"s", "")
		for j = 0; j <= i; j++ {
			fmt.Printf("%4d", number)
			number = number * (i - j) / (j + 1)
		}
		fmt.Println()
	}
}
Go Program to Print Pascal Triangle

It is another way of writing a golang program to print the pascals triangle of numbers.

package main

import "fmt"

func factorialCal(num int) int {
	if num == 0 || num == 1 {
		return 1
	}
	return num * factorialCal(num-1)
}
func main() {

	var i, j, num int

	fmt.Print("Rows to Print the Pascal Triangle = ")
	fmt.Scanln(&num)

	fmt.Println("\nPascal Triangle")
	for i = 0; i < num; i++ {
		for j = 1; j <= num-i-2; j++ {
			fmt.Print(" ")
		}
		for j = 0; j <= i; j++ {
			fmt.Printf("%d ", factorialCal(i)/(factorialCal(j)*factorialCal(i-j)))
		}
		fmt.Println()
	}
}
Rows to Print the Pascal Triangle = 8

Pascal Triangle
      1 
     1 1 
    1 2 1 
   1 3 3 1 
  1 4 6 4 1 
 1 5 10 10 5 1 
1 6 15 20 15 6 1 
1 7 21 35 35 21 7 1 

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.