C++ patterns
Any help on how to get this pattern printed?
**********
*********
********
*******
******
*****
****
***
**
*
The code I have prints it on the inverted side.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include<iostream>
using namespace std;
int main()
{
int row;
cout << "Enter an integer" << endl;
cin >> row;
for (int i = 1; i <= row; ++i)
{
for (int j = row; j >= i; j--)
{
cout << '*';
}
cout << endl;
}
}
|
I assume you mean
Think of it like printing two distinct characters, except the o's become spaces:
*****
o****
oo***
ooo**
oooo* |
So, every row, you need to print X amount of the first character, and (length - X) amount of the second character.
1 2 3 4 5 6 7 8 9
|
for (each row)
{
for (X amount of times)
print 'o'
for (row - X amount of times)
print '*'
print newline
}
|
Once you see the pattern and can print it, change the 'o's back to spaces.
Last edited on
You only need 1 for loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int row;
cout << "Enter an integer: ";
cin >> row;
for (int i = 0; i < row; ++i)
cout << setfill('*') << setw(row - i + 1) << '\n';
}
|
or for right aligned,
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int row;
cout << "Enter an integer: ";
cin >> row;
for (int i = 0; i < row; ++i)
cout << setfill(' ') << setw(i) << "" << setfill('*') << setw(row - i + 1) << '\n';
}
|
Last edited on
Thanks guys. This is the code I ended with. It works well...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include<iostream>
using namespace std;
int main()
{
int i,k,j,n;
cout << "Enter an integer" << endl;
cin >> n;
{
k=0;
for(i=n;i>0;i--)
{
for(j=1;j<=k;j++) std::cout<<" ";
for(j=1;j<=i;j++) std::cout<<"*" ;
std::cout<<"\n" ;
k++;
}
}
}
|
Topic archived. No new replies allowed.