### Pyramid Display

I know i am missing a for loop somewhere. I want to make this display a pyramid, im practicing my nested loops because it has been a while.

Heres my code

 ``123456789101112131415161718192021222324252627282930`` ``````// INCLUDES #include "stdafx.h" #include using namespace std; // MAIN int main() { // This program will display a pyramid for (int i = 1 ; i < 10 ; i+=2) { cout << "\n"; for (int j = 1 ; j <= i ; j++) { cout << "*"; } } cout << "\n\n"; // To Exit cout << "Press ENTER to exit..."; cin.clear(); cin.sync(); cin.get(); return 0; }``````

this displays

*
**
***
****
*****
******
*******
********
*********
**********

but it should look like this with spaces at the left to put it in the center

 ``12345678`` `````` * *** ***** ******* ********* *********** *************``````

ANY HELP
Last edited on
Just missing some logic. The top of the pyramid has one star and there is 9 spaces before that. Next line has 3 stars and there is 7 spaces before those 3 stars. To get the number of spaces to print before the first star you do (number_of_spaces_last_row_is_from_edge + length_of_pyramid).

So your last for-loop should come before line 13 and should just print the spaces
Last edited on
You have to add one more for loop to print out space before the stars.

 ``1234567891011121314`` ``````int size = 10; // size of pyramid int space = size; for (int i = 1 ; i < size; i+=2 ){ cout << "\n"; // print the spaces for (int j = 1 ; j < space ; j++){ cout << " "; } space--; // as we go down, we have less space to print for (int j = 1 ; j <= i ; j++){ cout << "*"; } }``````
Last edited on
 ``1234567891011121314151617181920212223242526272829303132333435363738394041`` ``````#include using namespace std; // MAIN int main() { // This program will display a pyramid int spaces = 10; int stars = 1; int size = 10; int i = 0; int j = 0; int x = 0; for (i = 0; i < size; i++) { for (j = 0; j <= spaces; j++) { cout << ' '; } spaces--; for(x = 0; x < stars; x++) { cout << '*'; } stars += 2; cout << endl; } cout << "\n\n"; // To Exit cout << "Press ENTER to exit..."; cin.ignore(); return 0; }``````
Thank you everyone for your help.
Enjoy!:)

 ``123456789101112131415161718192021222324252627`` ``````#include #include int main() { while ( true ) { const char asterisk = '*'; std::cout << "Enter a non-negative number: "; size_t n = 0; std::cin >> n; if ( !n ) break; std::cout << std::endl; for ( size_t i = 0; i < n; i++ ) { std::cout << std::setw( n - i ) << std::setfill( ' ' ) << asterisk; std::cout << std::setw( 2 * i + 1 ) << std::setfill( asterisk ) << '\n'; } std::cout << std::endl; } }``````
Last edited on
This question come up soooooo many times.
Topic archived. No new replies allowed.