PROWAREtech

articles » current » c-plus-plus » draw-ascii-diamond

C/C++: Draw ASCII Diamond

Not so easy to do.

Draw a diamond using characters in a console application. Output:

Enter the number of rows desired to make a diamond pattern (0 to quit): 9
    0
   000
  00000
 0000000
000000000
 0000000
  00000
   000
    0
Enter the number of rows desired to make a diamond pattern (0 to quit): 0
Press any key to continue
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
	bool go = true;

	while(go)
	{
		int charswide;
		cout << "Enter the number of rows desired to make a diamond pattern (0 to quit): ";
		cin >> charswide;
		go = (charswide > 0);
		int chdiamond = 1, charswide2 = charswide * 2;
		for(; chdiamond < charswide2; chdiamond += 2)
		{
			int chcount = (chdiamond <= charswide) ? chdiamond : (charswide2 - chdiamond);
			int j, spaces = (charswide - chcount) / 2;
			for(j = 0; j < spaces; j++)
			{
				cout << " ";
			}
			for(j = 0; j < chcount; j++)
			{
				cout << "0";
			}
			cout << endl;
		}
	}
	return 0;
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE