ProgramGuru

Pattern Programs

Start with Pattern Programs

Learn pattern programs through an executable example, then connect the small demonstration to production code.

What you’ll learn

  • Explain the main purpose of pattern programs.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Pattern printing uses nested loops to convert row and column positions into text. Practice by deciding what each row should contain before writing code.

This program builds each line in a strings.Builder and prints a right triangle made from asterisks.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for example patternsThe inner loop determines the width of each row.Set row countStep 1Loop through rowsStep 2Write row starsStep 3Print each lineStep 4The inner loop determines the width of each row.
The inner loop determines the width of each row.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"strings"
)

func main() {
	for row := 1; row <= 4; row++ {
		var line strings.Builder
		for col := 0; col < row; col++ {
			line.WriteByte('*')
		}
		fmt.Println(line.String())
	}
}

Output

*
**
***
****

Trace what the program does

The outer loop advances through four rows. The inner loop writes as many stars as the current row number, producing one, two, three and four stars.

Avoid common mistakes

  • Use separate row and column variables for clarity.
  • Patterns are about loop reasoning; avoid complex string slicing when a builder or Repeat suffices.

Try it yourself

Change the program to print five rows and then an inverted triangle.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

How many stars are printed on row 3?
Choose one answer. You can try again.

Answer and explanation

3

Correct. The outer loop advances through four rows.

What you should remember

You have practiced Pattern Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Array Programs →