I am new to c++, and I have a problem displaying a pattern of the letter k in c++.
The letter displays pattern depending on the input size. Here is the sample display of two different sizes of pattern:
sample display input size: 4
**** ****
**** ****
**** ****
**** ****
********
********
********
********
**** ****
**** ****
**** ****
**** ****
input size: 2
** **
** **
****
****
** **
** **
And I am now writing the upper part of the pattern of the letter K Here is my code:
#include <iostream>
using namespace std;
int main() {
int s, t, i;
cout << "Enter the size: ";
cin >> t;
if (t <= 0) {
return 0;
}
for (int i = 1; i <= t; i++) {
for (int i = 1; i <= t; i++) {
cout << "*"
<< "";}
for (int i = 1; i <= t; i++) {
cout << " "
<< "";
}
for (int i = 1; i <= t; i++) {
cout << "*"
<< "";
}
cout << endl;
}
return 0;
}
If I input: the size: 4 In this code, its output :
**** ****
**** ****
**** ****
**** ****
And I don't know how to write the code to subtract one space in each line after printing the first line. Can someone help me, please?
I want the result of my upper part of letter pattern should look like this: Size: 4
**** ****
**** ****
**** ****
**** ****
As mentioned in the comments, you should break up the writing of the
Kinto three logical operations. Also mentioned is using thestd::stringconstructor that takes a character count and a single character can be used instead of so manycoutstatements, outputting a single character each time.The three logical operations are as follows:
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, whereNis the number of stars, andXis the number of spaces. You see thatXis reduced by one for each line, and there are a total ofNlines.If you were to write a function to do this, it would look something like this:
The
nStarsis the number of stars (in your first example,nStarswould be 4), and thestarsis just a string ofnStarsstars. ThespaceCountis the number of spaces between the 4 stars. Note howspaceCountis reduced by 1 each time.That function effectively writes the top third of the
K.For the middle portion, it is simply
2 * Nstars, repeated forNlines.For the bottom third, it is similar to the top-third of the
K, except the number of spaces between the stars increases:'Putting this all together, you get the final program:
Live Example