I'm attempting to write a program that makes an hourglass design using asterisks (*).The user inputs a number of rows and the program makes the hourglass based on how many rows are specified.
Here is an example: This would show if 5 was entered.
*****
-***
--*
-***
*****
This is what I have so far:
int main()
{
int n, rows;
cout %26lt;%26lt; "Enter number of rows (no more than 23):" %26lt;%26lt; flush;
cin %26gt;%26gt; rows;
for (n = 1; n %26lt;= rows; n++)
{
if (n %26lt;= rows)
cout %26lt;%26lt; '*' %26lt;%26lt; flush;
}
if ((rows + 1) % 2)
cout %26lt;%26lt; '*' %26lt;%26lt; flush;
else
cout %26lt;%26lt; " " %26lt;%26lt; flush;
return 0;
This amount of code gets me the first line of *'s. I can only use cntrl structures: if, if else, switch, while, for, do-while; and can only use single characters and single spaces. I'm not looking for the exact code because I do want to learn this, but I am stuck and any pointers would be greatly appreciated
C++ hourglass loop?
#include "CHourGlass.h"
#include %26lt;string%26gt;
#include %26lt;iostream%26gt;
using namespace std;
CHourGlass::CHourGlass(int aRows)
{
if( aRows %26lt; 3 || aRows %26gt; 23 )
throw new string("row number violation");
m_height = aRows;
m_width = 1+((aRows/2)*2);
}
CHourGlass::~CHourGlass()
{
}
void CHourGlass::display()
{
int iWidth = m_width;
for( int i = 0; i%26lt; m_height;i++)
{
cout %26lt;%26lt; center(abs(iWidth))%26lt;%26lt; endl;
iWidth-=2;
if( iWidth == -1)
iWidth -=2;
}
}
string CHourGlass::center( int iCount)
{
int iSpace = (m_width-iCount)/2;
string result = string(iSpace,' ')+string(iCount, '*');
return result;
}
Reply:The first thing you need to do is identify the algorithm/relationship that you want your program to reflect. For example, given the number of rows the user wants, how do you calculate the number of stars each row will have? From your example of 5 rows it appears that you do:
5
5-2
5-2-2
5-2
5
Which would reflect an hourglass, however what if you only have 4 or 3 or 2 rows?
Identify this first and your program will easily fall into place.
Good luck!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment