Friday, July 31, 2009

Need some Help in C++?

I am trying to get this shape:


*


**


***


****


*****


******


*****


****


***


**


*





To not hug the siding but to look like a diamond. Can anyone show me how to do that? My code:





#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;


#include %26lt;string%26gt;





using namespace std;





int printTopStars(int num);


int printBottomStars(int num);





int main()


{


int num;


int num2;








cout %26lt;%26lt; " Enter the number of stars in the largest row of the pyramid: " %26lt;%26lt; endl;


cin %26gt;%26gt; num;


num2 = num;


printTopStars(num);


printBottomStars(num2);


return 0;


}


int printTopStars(int num)


{





if(num == 0)


return 0;


else


for (int row = 1; row %26lt;= num; row++)


{


for (int col = 0; col %26lt; row; col++)


{


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


}


cout %26lt;%26lt; endl; // end the line.


}





return printTopStars(0);


}


int printBottomStars(int num)


{


int counter = 0;


if(num == 0)


return 0;


else


for(counter;counter %26lt; num; counter++)


{


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


}


cout %26lt;%26lt; endl;





return printBottomStars(num - 1);


}





Thanks!

Need some Help in C++?
I cleaned up your code somewhat.





#include %26lt;iostream%26gt;





using namespace std;





void printStars(int num, int step)


{


   int begin = step == 1 ? 1 : num;


   int end = step == 1 ? num : 0;





   for (int row = begin; row != end; row += step)


   {


      for (int space = 0; space %26lt; num - row; space++)


      {


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


      }





      for (int col = 0; col %26lt; row; col++)


      {


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


      }


      cout %26lt;%26lt; endl;


   }


}





int main()


{


   int num;


   cout %26lt;%26lt; "Enter the number of stars in the largest row of the pyramid: " %26lt;%26lt; endl;


   cin %26gt;%26gt; num;


   printStars(num, +1); // +1 = the number of stars increases per row, -1 = it decreases.


   printStars(num, -1);


   return 0;


}
Reply:Computer Tutorials, Interview Question And Answer


http://freshbloger.com/
Reply:You need to output spaces before the stars. Say the number of stars in the current row is x, and the largest row of stars is num. In the current row, you need to output x-num spaces before the stars. Then it will look like a dimond.


No comments:

Post a Comment