Patterns using loops

I need to print this pattern
# # # # # # # # #
@ # # # # # # # #
@ @ # # # # # # #
@ @ @ # # # # # #
@ @ @ @ # # # # #
@ @ @ @ @ # # # #
@ @ @ @ @ @ # # #
@ @ @ @ @ @ @ # #
@ @ @ @ @ @ @ @ #

I did this .. but its wrong, its almost near
What is wrongg with this ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22


#include <iostream>
#include <iomanip>


using namespace std;

void main()
{
	
	for (int i = 1; i <= 9; i++)
	{
		for (int j = 10 - i; j > 0; j--)
			cout << setw(2) << "#";

		for (int k = 9; k <= i; k++)
			cout << setw(2)<< "@";
		cout << endl;
	}
	system("pause");
}
Last edited on
Think about this:
1
2
3
4
5
6
7
8
9
10
int col = 0;
while ( col < 7 ) {
  std::cout << 'a';
  ++col;
}
while ( col < 42 ) {
  std::cout << 'h';
  ++col;
}
std::cout << '\n';
You have the right idea, you just need to adjust your counters. Also, you need to print the '@' characters first and the '#' characters second.

When doing a problem like this, it's really helps to draw up a table that shows how many of each character you have to print:
Line	'@'	'#'
-----------------
1	0	9
2	1	8
3	2	7
...
9	8	1


Now write the number of '@' and '#' characters you print as a function of the line number. For example, the number of '@' characters is "line number minus 1".

Now transfer this to your code.
@dhayden
Would this be correct ?


1
2
3
4
5
6
7
8
 for (int i = 1; i <= 9; i++)
	{

		for (int k = 0; k <= i; k++)
			cout << setw(2) << "@";

		for (int j = 10 -i; j > 0; j--)
			cout << setw(2) << "#"; 
That's certainly a lot closer. Run it and see what you get. Adjust the loop bounds if things aren't right.
Topic archived. No new replies allowed.