Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Basics

Floyd's Triangle

Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant

Print Floyd's triangle with n rows: row i contains the next i consecutive numbers, starting from 1.

Input

A single integer n.

Output

n lines; the numbers in each line are separated by a single space.

Constraints

Example 1

Input

4

Output

1
2 3
4 5 6
7 8 9 10

Example 2

Input

1

Output

1

Hints

  1. Row i has exactly i numbers.
  2. Keep one counter that keeps increasing across rows.

Approach

Two nested loops: the outer one over rows 1..n, the inner one printing i numbers. A single counter k, starting at 1, is printed and incremented each time — it never resets between rows.

Complexity: O(n²) time · O(1) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    int k = 1;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) cout << k++ << (j < i ? " " : "\n");
    }
    return 0;
}

Python solution

n = int(input())
k = 1
for i in range(1, n + 1):
    print(*range(k, k + i))
    k += i

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();
        StringBuilder sb = new StringBuilder();
        int k = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) sb.append(k++).append(j < i ? " " : "\n");
        }
        System.out.print(sb);
    }
}

Solve Floyd's Triangle online · All practice problems