Floyd's Triangle in Dart — With Code, Output & Explanation

· 4 min read

⚡ TL;DR

Print Floyd's Triangle in Dart using nested loops and a running counter. Full working code with output, plus variations like reverse Floyd's and right alignment.

Floyd’s Triangle is a right-angled triangle of consecutive natural numbers. The first row has 1 number, the second has 2, and so on — but the numbers keep incrementing across rows instead of resetting. It’s a classic loop exercise for mastering state that persists across iterations.

Pattern to Print

Copy
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Implementation

Copy
void main() {
  int n = 5;
  int counter = 1;

  for (int i = 1; i <= n; i++) {
    List<String> row = [];
    for (int j = 0; j < i; j++) {
      row.add(counter.toString());
      counter++;
    }
    print(row.join(" "));
  }
}

Output

Copy
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

How It Works

A single counter increments with every printed number, and row i contains exactly i numbers. The key insight: the counter lives outside the inner loop, so it persists across rows. That’s what makes Floyd’s Triangle different from patterns where each row resets to 1 2 3....

Variation: Right-Aligned Floyd’s

Pad each number to a fixed column width so the triangle’s right edge lines up:

Copy
void main() {
  int n = 5;
  int counter = 1;
  int maxNum = n * (n + 1) ~/ 2;          // last number printed
  int width = maxNum.toString().length;    // column width for alignment

  for (int i = 1; i <= n; i++) {
    List<String> row = [];
    for (int j = 0; j < i; j++) {
      row.add(counter.toString().padLeft(width));
      counter++;
    }
    print(row.join(" "));
  }
}

Output

Copy
 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15

n * (n + 1) ~/ 2 is the closed-form for the last number (sum of 1..n), used to compute the padding width.

Variation: Reverse Floyd’s Triangle

Count downward, starting each row from where the previous row would have ended:

Copy
void main() {
  int n = 5;
  int total = n * (n + 1) ~/ 2;

  for (int i = 1; i <= n; i++) {
    List<String> row = [];
    int start = total - i + 1;
    for (int j = 0; j < i; j++) {
      row.add((start + j).toString());
    }
    print(row.join(" "));
    total -= i;
  }
}

Output

Copy
15
13 14
10 11 12
6 7 8 9
1 2 3 4 5

Practice Variations

  1. Fibonacci Floyd’s: fill the rows with Fibonacci numbers instead of consecutive integers
  2. Even-only Floyd’s: print 2, 4, 6, 8… in triangle form
  3. Pyramid Floyd’s: center the numbers like a pyramid instead of left-aligning
  4. Modify the code to accept the triangle size as user input

Each variation exercises the same skill: tracking state across loop iterations. Master this and the harder pattern problems become straightforward.

Complexity

  • Time: O(n²) — prints n(n+1)/2 numbers
  • Space: O(n) — one row buffer at a time

FAQ

How do you print the Floyd’s Triangle pattern in Dart?

Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Dart implementation with expected output is shown in the sections above.

What is the time complexity of the Floyd’s Triangle pattern in Dart?

The time complexity is O(n²) and the space complexity is O(n), since the pattern is built with a fixed number of loop counters and printed row by row.

Happy coding!

Related Blogs
Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlock Flutter's potential with clean code. Learn best practices for writing maintainable Dart code, with examples and essential principles.

CLEAN CODECODE BEST PRACTICESCODE MAINTAINABILITYCODE ORGANIZATIONCODE READABILITY

June 02, 2023

Top 9 Local Databases for Flutter: Full Comparison

Top 9 Local Databases for Flutter: Full Comparison

Compare the best local databases for Flutter (Isar, Hive, Sqflite, ObjectBox, Realm, Drift, Floor, CBL, Sembast). Find pros, cons, and performance comparisons.

CODINGFLUTTERFLUTTER LOCAL DATABASESLEARN TO CODENOSQL

April 06, 2023

Related Tutorials
Essential Git Skills: How to Delete Remote Branches

Essential Git Skills: How to Delete Remote Branches

Keep your repository clean and organized. This guide walks you through how to delete both local and remote branches in Git, step by step.

BITBUCKETDELETE LOCAL BRANCHDELETE REMOTE BRANCHGITGIT BRANCH CLEANUP AUTOMATION

June 12, 2024

Show an Offline Message for No Internet in Flutter

Show an Offline Message for No Internet in Flutter

You have to use the 'Connectivity Flutter Package' to achieve this feature on your App. This package helps to know whether your device is online or offline.

CONNECTIVITY PLUSDEPENDENCIESFLUTTERFLUTTER DEVELOPMENTFLUTTER PACKAGES

April 09, 2024

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Implement TabBar and TabBarView in Flutter step by step — customize tab indicators, enable scrollable tabs, and change tabs programmatically.

CODINGDEFAULT TAB CONTROLLERFLUTTERLEARN TO CODETAB CONTROLLER

July 26, 2023

File Manipulation in Flutter: Best Practices & Examples

File Manipulation in Flutter: Best Practices & Examples

Master Flutter file manipulation — permission management, directory handling, and practical read-write scenarios to elevate your app's file handling.

CODINGFLUTTERFLUTTER DEVELOPMENTFLUTTER FILE OPERATIONFLUTTER PATH PROVIDER

June 30, 2023

Related Recommended Services
Visual Studio Code for the Web

Visual Studio Code for the Web

Build with Visual Studio Code, anywhere, anytime, in your browser.

IDEVISUAL STUDIOVISUAL STUDIO CODEWEB
Renovate | Automated Dependency Updates

Renovate | Automated Dependency Updates

Renovate Bot keeps source code dependencies up-to-date using automated Pull Requests.

AUTOMATED DEPENDENCY UPDATESBUNDLERCOMPOSERGITHUBGO MODULES
Best XML Formatter and XML Beautifier

Best XML Formatter and XML Beautifier

Online XML Formatter will format xml data, helps to validate, and works as XML Converter. Save and Share XML.

XMLXML BEAUTIFIERXML CONVERTERXML FORMATXML FORMATTER
Kubecost | Kubernetes cost monitoring and management

Kubecost | Kubernetes cost monitoring and management

Kubecost started in early 2019 as an open-source tool to give developers visibility into Kubernetes spend. We maintain a deep commitment to building and supporting dedicated solutions for the open source community.

CLOUDKUBECOSTKUBERNETESOPEN SOURCESELF HOSTED
Related Recommended Stories
How GitHub reduced testing time for iOS apps with new runner features

How GitHub reduced testing time for iOS apps with new runner features

Learn how GitHub used macOS and Apple Silicon runners for GitHub Actions to build, test, and deploy our iOS app faster.

IOSGITHUBTESTINGRUNNER
5 ways to transform your workflow using GitHub Copilot and MCP

5 ways to transform your workflow using GitHub Copilot and MCP

Learn how to streamline your development workflow with five different MCP use cases.

AGENT MODECODING AGENTCOPILOTFIGMAGITHUB
One weird trick for powerful Git aliases

One weird trick for powerful Git aliases

Advanced Git Aliases

ALIASALIAS TEMPLATEATLASSIANBITBUCKETGIT
Awesome Python

Awesome Python

An opinionated list of awesome Python frameworks, libraries, software and resources

AWESOMEAWESOME PYTHONCOLLECTIONSGITHUBPYTHON
Related Recommended Tools
Find out what websites are built with - Wappalyzer

Find out what websites are built with - Wappalyzer

Find out the technology stack of any website. Create lists of websites and contacts by the technologies they use.

ADD ONSANALYTICSAPP STOREAPPLEBOOKING
Sourcetree | Free Git GUI for Mac and Windows

Sourcetree | Free Git GUI for Mac and Windows

A Git GUI that offers a visual representation of your repositories. Sourcetree is a free Git client for Windows and Mac.

GITGITHUBGITLABATLASSIANBITBUCKET
Related Recommended Videos