Triangular numbers are a sequence of numbers that can be represented in the shape of an equilateral triangle. They are obtained by adding the natural numbers. For example, the first triangular number is 1, the second is 1 + 2 = 3, the third is 1 + 2 + 3 = 6, and so on. Triangular numbers have various applications in mathematics and computer science. In this article, we will explore how to generate and work with triangular numbers in C++.
A triangular number or triangle number is a number that can be represented in the form of a triangular grid of points where the first row contains one point, the second row contains two points, and so on. The n-th triangular number is the sum of the first nnn natural numbers.
The formula to calculate the n-th triangular number Tn is:
Tn=n×(n+1)/2
#include <iostream>
#include <vector>
// Function to generate the first n triangular numbers
std::vector<int> generateTriangularNumbers(int numberOfTerms) {
std::vector<int> triangularNumbers;
for (int n = 1; n <= numberOfTerms; ++n) {
int triangularNumber = (n * (n + 1)) / 2;
triangularNumbers.push_back(triangularNumber);
}
return triangularNumbers;
}
int main() {
int numberOfTerms = 10;
std::vector<int> triangularNumbers = generateTriangularNumbers(numberOfTerms);
std::cout << "First " << numberOfTerms << " triangular numbers: ";
for (int num : triangularNumbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
std::vector<int> generateTriangularNumbers(int numberOfTerms) {
std::vector<int> triangularNumbers;
for (int n = 1; n <= numberOfTerms; ++n) {
int triangularNumber = (n * (n + 1)) / 2;
triangularNumbers.push_back(triangularNumber);
}
return triangularNumbers;
}
This function generates the first numberOfTerms
triangular numbers. It initializes an empty vector triangularNumbers
and uses a for
loop to calculate each triangular number using the formula (n∗(n+1))/2. Each calculated triangular number is then added to the vector.
int main() {
int numberOfTerms = 10;
std::vector<int> triangularNumbers = generateTriangularNumbers(numberOfTerms);
std::cout << "First " << numberOfTerms << " triangular numbers: ";
for (int num : triangularNumbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
In the main
function, we define the number of terms for the triangular number sequence. We then call the generateTriangularNumbers
function with this parameter to generate the sequence. Finally, we print the sequence to the console.
When the above code is executed, it produces the following output:
First 10 triangular numbers: 1 3 6 10 15 21 28 36 45 55
This output shows the first ten triangular numbers. Each number is the sum of the natural numbers up to that point, illustrating the triangular number pattern.