Reputation: 11
for (int i = 1; i <= 4; i++)
{
int n = 4;
for (int j = 1; j <= n - i; j++)
{
System.out.print(" ");
}
for (int k = i; k >= 1; k--)
{
System.out.print(k);
}
for (int l = 2; l <= i; l++)
{
System.out.print(l);
}
System.out.println();
}
for (int i = 3; i >= 1; i--)
{
int n = 3;
for (int j = 0; j <= n - i; j++)
{
System.out.print(" ");
}
for (int k = i; k >= 1; k--)
{
System.out.print(k);
}
for (int l = 2; l <= i; l++)
{
System.out.print(l);
}
System.out.println();
}
My output:
Enter height:
12
1
212
32123
4321234
543212345
65432123456
7654321234567
876543212345678
98765432123456789
109876543212345678910
1110987654321234567891011
12111098765432123456789101112
It prints correctly, but with no spacing... Would I need another for loop with a println that just prints a space under the first for loop?
Also, if I did that would it still work for double digit heights such as 12?
I would greatly appreciate help, thank you.
Upvotes: 0
Views: 103
Reputation: 1171
You just need to play around with spaces.
for (int i = 1; i <= height; i++) {
int n = height;
int n2 = height + 1;
for (int j = 1; j <= n - i; j++) {
System.out.print("" + String.format("%3s", " ") + " ");
}
for (int k = i; k >= 1; k--) {
System.out.print("" + String.format("%3s", k) + " ");
}
for (int l = 2; l <= i; l++) {
System.out.print("" + String.format("%3s", l) + " ");
}
System.out.println();
System.out.println();
}
OUTPUT: For height 10
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
Upvotes: 2