Number Triangle in C++
A number triangle in C++ is a pattern of numbers printed in the form of a triangle. Typically, each row of the triangle contains a sequence of numbers that follow a specific pattern. You can create various number triangles depending on the pattern you want to achieve. Here’s an example of a simple number triangle in C++:
#include <iostream>
int main() {
int n;
// Input the number of rows for the triangle
std::cout << "Enter the number of rows: ";
std::cin >> n;
// Loop to print the number triangle
for (int i = 1; i <= n; ++i) {
// Print spaces for formatting
for (int j = 1; j <= n - i; ++j) {
std::cout << " ";
}
// Print numbers in ascending order
for (int k = 1; k <= i; ++k) {
std::cout << k << " ";
}
// Print numbers in descending order (excluding 1)
for (int l = i - 1; l >= 1; --l) {
std::cout << l << " ";
}
// Move to the next line
std::cout << std::endl;
}
return 0;
}
In this example, the program prompts the user to enter the number of rows for the number triangle. It then uses nested loops to print the numbers in a triangular pattern. Each row contains ascending and descending numbers, with spaces for formatting.
For example, if you enter 5
as the number of rows, the program will generate the following output:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
You can modify the pattern and the number of rows to create different types of number triangles according to your requirements.