Printing a Dimond patteren with numbers

Hi I'm new to programming I had to complete a task to print a diamond with numbers i did all the logic's but cant seem to figure out the spacing it dosen't make a diamond please help! Here's my code


#include<iostream>
using namespace std;

int main()
{
int num = 1;
for (int i = 0; i <= 5; i++)
{
for (int j = 1; j <= 9/2+1 - i; j++)
{
cout << " ";
}
for (int k = 1; k <= i; k++)
{
cout << num << " ";
num++;
}
cout << endl;
}
for (int i = 9; i > 5; i--)
{
for (int j = 9; j >=i; j--)
{
cout << " ";
}
for (int k = i; k > 5; k--)
{
cout << num<< " ";
num++;
}
cout << endl;
}

system("pause");
return 0;
}
First, if you use code tags and format your code you'll get a response much faster.

Your code looks pretty good, you just need to adjust for some numbers having one digit and some having 2 or more.

There are several ways to do that but the one that changes your code the least is just to add a 0 or space if the number is less than 10.

See the below example using code tags.

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
26
27
28
29
30
31
32
33
34
#include<iostream>
using namespace std;

int main()
{
int num = 1;
for (int i = 0; i <= 5; i++)
	{
		for (int j = 1; j <= 9/2+1 - i; j++)
			{cout << " ";}
		for (int k = 1; k <= i; k++)
			{
			if (num < 10)
				{cout << "0";}
			cout << num << " ";
			num++;
			}
		cout << endl;
	}
for (int i = 9; i > 5; i--)
	{
	for (int j = 9; j >=i; j--)
		{cout << " ";}
	for (int k = i; k > 5; k--)
		{
		cout << num<< " ";
		num++;
		}
	cout << endl;
	}

//system("pause");
return 0;
}
Last edited on
Topic archived. No new replies allowed.