inverted triangle c++
To create an inverted triangle using C++, you can use nested loops. Here's the code with explanations for each step:
#include <iostream>
int main() {
int rows = 5; // Number of rows in the inverted triangle
for (int i = 0; i < rows; i++) {
// Print spaces before each row
for (int j = 0; j < i; j++) {
std::cout << " ";
}
// Print asterisks for each row
for (int k = 0; k < (2 * (rows - i) - 1); k++) {
std::cout << "*";
}
// Move to the next line
std::cout << std::endl;
}
return 0;
}
Explanation for each step:
We start by including the
iostream
library to enable input/output operations.The
main()
function is the entry point of the program.We declare and initialize the variable
rows
to determine the number of rows in the inverted triangle. You can modify this value to adjust the size of the triangle.We start a
for
loop with the variablei
to iterate through each row of the triangle. The loop runs untili
is less thanrows
.Inside the outer loop, we start another
for
loop with the variablej
to print the spaces before each row. The number of spaces is equal to the value ofi
.After the inner loop, we start another
for
loop with the variablek
to print the asterisks for each row. The number of asterisks is calculated using the formula(2 * (rows - i) - 1)
. This formula ensures that the number of asterisks decreases by 2 for each row.Finally, we use
std::endl
to move to the next line after printing each row.The program ends by returning 0 from the
main()
function.
This code will produce an inverted triangle with the specified number of rows.