Jerielle Jerielle - 2 months ago 12
C++ Question

how to create a pyramid using for loop in c++

Hello guys I just want to ask how can I create a triangle using c++. Actually I have my code but I don't have an idea how to center the first asterisk in the triangle. My triangle is left align. How can I make it a pyramid? Heres my code below. Sorry for the format because I am using a phone only.

#include<iostream>
using namespace std;

int main(){

int x,y;
char star = '*';
char space = ' p ';
int temp;


for(x=1; x <= 23; x++){

if((x%2) != 0){

for(y=1; y <= x ; y++){

cout << star;

}


cout << endl;

}

}

return 0;
}

Answer

To calculate the number of spaces needed to center each row use this algorithm:

numSpaces = (23 - x) / 2;

and then a for loop to apply the spaces numSpaces times.

Here is the complete code:

#include<iostream>
using namespace std;

int main(){

    int x,y;
    char star = '*';
    char space = ' p ';
    int temp;
    int numSpaces = 0;

    for(x=1; x <= 23; x++){ 

        if((x%2) != 0){
            numSpaces = (23 - x) / 2;  // Calculate number of spaces to add

            for(int i = 0; i < numSpaces; i++) // Apply the spaces
            {
                cout << " ";
            }       

            for(y=1; y <= x ; y++){     

                cout << star;                   

            }   
            cout << endl;
        }
    }
    return 0;
}

And the output:

           *
          ***
         *****
        *******
       *********
      ***********
     *************
    ***************
   *****************
  *******************
 *********************
***********************
Comments