As mentioned in the comments, you should break up the writing of the K
into three logical operations. Also mentioned is using the std::string
constructor that takes a character count and a single character can be used instead of so many cout
statements, outputting a single character each time.
The three logical operations are as follows:
- Writing the top third of the letter 'K'
- Writing the middle section of the letter 'K'
- Writing the lower third of the letter 'K'
Note that each operation can be made generic if you look closely at the pattern that is associated with that section of the letter.
For the top-third, it has a pattern of:
N stars X spaces, N stars
, where N
is the number of stars, and X
is the number of spaces. You see that X
is reduced by one for each line, and there are a total of N
lines.
If you were to write a function to do this, it would look something like this:
#include <iostream>
#include <string>
void drawTop(int nStars)
{
std::string stars(nStars, '*');
for (int spaceCount = nStars; spaceCount > 0; --spaceCount)
std::cout << stars << std::string(spaceCount, ' ') << stars << "\n";
}
The nStars
is the number of stars (in your first example, nStars
would be 4), and the stars
is just a string of nStars
stars. The spaceCount
is the number of spaces between the 4 stars. Note how spaceCount
is reduced by 1 each time.
That function effectively writes the top third of the K
.
For the middle portion, it is simply 2 * N
stars, repeated for N
lines.
void drawMiddle(int nStars)
{
std::string s(nStars * 2, '*');
for (int i = 0; i < nStars; ++i)
std::cout << s << "\n";
}
For the bottom third, it is similar to the top-third of the K
, except the number of spaces between the stars increases:'
void drawTop(int nStars)
{
std::string stars(nStars, '*');
for (int spaceCount = 1; spaceCount <= nStars; ++spaceCount)
std::cout << stars << std::string(spaceCount, ' ') << stars << "\n";
}
Putting this all together, you get the final program:
#include <iostream>
#include <string>
void drawTop(int nStars)
{
std::string stars(nStars, '*');
for (int spaceCount = nStars; spaceCount > 0; --spaceCount)
std::cout << stars << std::string(spaceCount, ' ') << stars << "\n";
}
void drawMiddle(int nStars)
{
std::string s(nStars * 2, '*');
for (int i = 0; i < nStars; ++i)
std::cout << s << "\n";
}
void drawBottom(int nStars)
{
std::string stars(nStars, '*');
for (int spaceCount = 1; spaceCount <= nStars; ++spaceCount)
std::cout << stars << std::string(spaceCount, ' ') << stars << "\n";
}
void drawAllStars(int nStars)
{
drawTop(nStars);
drawMiddle(nStars);
drawBottom(nStars);
}
int main()
{
drawAllStars(4);
std::cout << "\n\n";
drawAllStars(2);
std::cout << "\n\n";
drawAllStars(5);
std::cout << "\n\n";
drawAllStars(3);
}
Live Example