Introduction
Code Implementation
Method 1:
#include <iostream>
int main() {
int height = 5;
for (int i = 1; i <= height; ++i) {
// Print spaces for alignment
for (int s = 1; s <= height - i; ++s) {
std::cout << " ";
}
// Print stars in the right triangle
for (int j = 1; j <= i; ++j) {
std::cout << "*";
}
// Move to the next line after each row
std::cout << std::endl;
}
return 0;
}
// Output
*
* *
* * *
* * * *
* * * * *
Explanation:
- The outer loop (
for (int i = 1; i <= height; ++i)
) iterates through each row, wherei
represents the current row number. - The first inner loop (
for (int s = 1; s <= height - 1; ++s)
) prints spaces to align the stars to the right. The number of spaces is equal toheight - i
. - The second inner loop (
for (int j = 1; j <= i; ++i)
) prints the stars in the right triangle pattern, starting from 1 and incrementing up to the current row number. - The
std::endl
is used to move to the next line after printing each row.
Method 2:
#include <iostream>
int main() {
int height = 5;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < height; j++) {
if (j < height - i - 1) {
std::cout << " ";
} else {
std::cout << "* ";
}
}
// Move to the next line after each row
std::cout << std::endl;
}
return 0;
}
// Output
*
* *
* * *
* * * *
* * * * *
Complexity Analysis
Time Complexity: The time complexity of generating a right triangle pattern using nested loops is O(n^2)
, where n
is the height of the triangle.