Tuesday, July 28, 2009

Need a help with a Pyramid for C++?

Im new to C++ and wonder if anybody can help me out.


I need to center this pyramid this is what ive done


#include %26lt;iostream%26gt;


using name space std


int main ()


{


int j,i


for (i=1; i%26lt;=5; i++)


{


for (j=1; j%26lt;i; j++)


cout %26lt;%26lt; "*";


cout %26lt;%26lt; endl;


}


having this result


*


**


***


****


*****


I need to center it so it can look like a PYRAMID with asterics.

Need a help with a Pyramid for C++?
#include %26lt;iostream%26gt;


using namespace std;





void print_pyramid(int height);





int main()


{





print_pyramid(10);





return 0;


}


void print_pyramid(int height)


{


int line;


int const MARGIN = 10;





cout %26lt;%26lt; "\n\n";





for (line = 1 ; line %26lt;= height ; line++)


{


int count;


int total_no_of_spaces = MARGIN + height - line;





for (count = 1 ; count %26lt;= total_no_of_spaces ; count++)


cout %26lt;%26lt; ' ';





for (count = 1 ; count %26lt;= line * 2 ; count++)


cout %26lt;%26lt; '*';





cout %26lt;%26lt; '\n';


}





cout %26lt;%26lt; "\n\n";


}
Reply:Here you go:





// NOTE: I'm using dashes "-----" below just to leave space.


// Don't use them in your actual program.





// n = the pyramid's number of rows (levels)





// The following for-loop does some work to each level of the


// pyramid


for (int i = 0; i %26lt; n; i++)


{


------ // The following for-loop prints the appropriate number of


------ // spaces


------ for (int j = i; j %26lt; n - 1; j++)


------ {


------------ cout %26lt;%26lt; " ";


------ }


------ // The following for-loop prints the appropriate number of


------ // asterics


------ for (int k = 0; k %26lt; ((i * 2) + 1); k++)


------ {


------------ cout %26lt;%26lt; "*";


------ }


------ cout %26lt;%26lt; endl;


}
Reply:You're going to have an issue with "centering" it... just think of the first two lines:


*


**


How do you center one asterisk over two of them? The only way is to put 1/2 space in front of the one asterisks. But you can't print a 1/2 space. And if this is a console application, odds are you're using a fixed font so changing the font for the spaces isn't going to help.





You can get close by adding a "spacing loop" between the two loops that goes from 1 to (5-i)/2 and prints a space each time through.

snow of june

No comments:

Post a Comment