Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Number Pattern: 1 to Row Triangle in C++

Print a single number triangle in C++ where row i counts 1, 2, ... up to i. A beginner nested-loop lesson that swaps the star for the inner counter j.

BeginnerPattern ProgramsExample 5 of 6
number-pattern-1-to-row-triangle.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int rows;
6
7 cout << "Enter number of rows: ";
8 cin >> rows;
9
10 for (int i = 1; i <= rows; i++) {
11 for (int j = 1; j <= i; j++) {
12 cout << j << " ";
13 }
14 cout << endl;
15 }
16
17 return 0;
18}

Sample Output

1

Row 1.

1 2 3 4 5

Row 5: j ran from 1 to 5.

In this one

  • How printing j instead of a star turns a star pattern into numbers
  • What i and j each mean in a nested loop
  • How changing j to i changes the pattern
  • Why numbers above 9 can break alignment

How it works

  1. 1

    Read rows (5).

  2. 2

    Outer loop picks row i.

  3. 3

    Inner loop prints j = 1 up to i, each followed by a space.

  4. 4

    endl ends the row.

Edge cases

Rows above 9

Enter 12.

Two-digit numbers take more room, so later rows look wider and uneven. Use setw from <iomanip> to fix the column width.

Printing i

Swap j for i in the cout.

Each row repeats its row number (1, 2 2, 3 3 3), a different pattern covered on the advanced number pattern page.

What's going on

Same nested shape as the right-half pyramid, but print j instead of *. Row i prints 1 2 … i.

for (int i = 1; i <= rows; i++)

for (int j = 1; j <= i; j++)

cout << j << " ";

Walk 5:

i=1: 1
i=2: 1 2
i=3: 1 2 3
i=4: 1 2 3 4
i=5: 1 2 3 4 5

cout << i instead of j and every row is the same digit: 1 / 22 / 333 / … That's a different homework.

j from i down to 1 prints 5 4 3 2 1 on the last row.

Spaces and centering are the left-half / full-pyramid trick. This program doesn't pad.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does row 4 print?

Pick an answer to check it.

Question 2

Which variable is printed in this program?

Pick an answer to check it.

Questions people ask

What is the last number on each row?

The row number i.

How many numbers are printed in total?

rows(rows+1)/2, the same count as the stars in a right half pyramid.

How do I count down instead?

Run j from i down to 1.