To print a Diamond Pattern in Perl, we use nested loops. The outer loop controls the rows and the inner loops control the spaces and stars (*) to form the pattern.
In this example,
printDiamond
that takes the desired number of rows n
as a parameter.for
loops, where the outer loop runs from 1 to n
and the inner loops control the spaces and stars in each row.sub printDiamond {
my ($n) = @_;
for my $i (1..$n) {
print ' ' x ($n - $i), '*' x (2 * $i - 1), "\n";
}
for my $i (reverse 1..$n-1) {
print ' ' x ($n - $i), '*' x (2 * $i - 1), "\n";
}
}
# Example usage
printDiamond(5);
* *** ***** ******* ********* ******* ***** *** *
In this tutorial, we learned How to print Diamond Pattern in Perl language with well detailed examples.