Java Example – Print a diamond
Output a diamond with a specified number of rows.
Example
public
class
Diamond
{
public
static
void
main
(
String
[
]
args
)
{
(
8
)
;
//
Output a diamond with 8 rows
}
public
static
void
(
int
size
)
{
if
(
size
%
2
==
0
)
{
size
++;
//
Calculate the diamond size
}
for
(
int
i
=
0
;
i
<
size
/
2
1;
i
++
)
{
for
(
int
j
=
size
/
2
1
;
j
i
1
;
j
--
)
{
System
.
out
.
(
"
"
)
;
//
Output the blank spaces at the top-left position
}
for
(
int
j
=
0
;
j
<
2
i
1;
j
++
)
{
System
.
out
.
(
"
"
)
;
//
Output the top half edge of the diamond
}
System
.
out
.
println
(
)
;
//
Newline
}
for
(
int
i
=
size
/
2
1
;
i
<
size
;
i
++
)
{
for
(
int
j
=
0
;
j
<
i
size
/
2;
j
++
)
{
System
.
out
.
(
"
"
)
;
//
Output the bottom-left blank of the diamond
}
for
(
int
j
=
0
;
j
<
2
size
1
2
i;
j
++
)
{
System
.
out
.
(
"
"
)
;
//
Output the bottom half edge of the diamond
}
System
.
out
.
println
(
)
;
//
Newline
}
}
}
Output result:
*
***
*****
*******
*********
*******
*****
***
*
Java Examples