c-plus-plus
  1. c-plus-plus-number-triangle

C++ Programs: Number Triangle

Number Triangle is a common programming task in which a pattern is printed using numbers. The pattern resembles a triangle, that is why it is called Number Triangle. It is a great way to practice nested loops in C++.

Syntax

for(int i=1;i<=n;i++){
    for(int j=1;j<=i;j++){
        cout<<j<<" ";
    }
    cout<<endl;
}

Example

#include <iostream>
using namespace std;

int main()
{
    int n;  
    cout<<"Enter the number of rows: ";  
    cin>>n;  
    for(int i=1;i<=n;i++){
        for(int j=1;j<=i;j++){
            cout<<j<<" ";
        }
        cout<<endl;
    }
    return 0;
}

Output

Enter the number of rows: 5
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

Explanation

In the above example, we have taken the input from the user and stored it in variable 'n'. Next, we have a nested loop which prints numbers from 1 to i, where i is the number of rows. The outer loop runs from 1 to n and the inner loop runs from 1 to i only. The pattern is printed using cout statements and endl is used to move to the next line after each row is printed.

Use

Number Triangle can be used to practice nested loops and to sharpen your pattern printing skills in C++. It can also be used to create visually appealing patterns for educational and entertainment purposes.

Important Points

  • Number Triangle is a popular programming task that helps to practice nested loops and pattern printing in C++.
  • The nested loop inside a loop runs from 1 to i only, where i is the current row number.
  • The cout statement is used to print the numbers and endl is used to move to the next line after each row is printed.

Summary

In summary, Number Triangle is a great way to practice nested loops in C++. You can print visually appealing patterns using numbers and polish your skills in pattern printing. Keep practicing and try to create more complex patterns using nested loops and other programming concepts.

Published on: