Pyramid Function
Write a function that prints a pyramid.
Each block of the pyramid should consist of [].
The function should take an int argument height.
If height isn't passed as an argument, it should print a pyramid of 5 height.
Use default parameter values to solve this task. Do not use function overloading.
#include <iostream>
// Pyramid function here
int main()
{
print_pyramid(3); // 3 line tall pyramid
print_pyramid(); // 5 line tall pyramid
}
[]
[][]
[][][]
[]
[][]
[][][]
[][][][]
[][][][][]
Hint
How to make a pyramid of x height:
- Make a for-loop that goes from 0 to
x, we'll reffer to the current number asy - At the end of each loop, go to a new line using
std::cout << "\n"; - Inside the loop; print
x-ynumber of spaces using another for-loop. - Then print
ynumber of boxes usingstd::cout << "[]";(you can use another for loop for this)
Answer
#include <iostream>
// NEW CODE START --------------------------------------
void print_pyramid(int height = 5) {
for (int y = 0; y < height; y++)
{
int box_count = y + 1;
int space_count = height - box_count;
for (int x = 0; x < space_count; x++)
std::cout << " ";
for (int x = 0; x < box_count; x++)
std::cout << "[]";
std::cout << "\n";
}
}
// NEW CODE END ----------------------------------------
int main()
{
print_pyramid(3); // 3 line tall pyramid
print_pyramid(); // 5 line tall pyramid
}