Search⌘ K

Solution Review: Make a Diamond

Explore a step-by-step review of a Perl solution that prints a diamond pattern using loops and operators. Understand how to apply the range operator and repetition to control output formatting for this classic programming exercise.

We'll cover the following...

Solution

Let’s look at the solution before jumping into the explanation:

Perl
# Assume that $n is already defined
for my $i (0..$n)
{
print ' ' x ($n-$i);
say 'o' x (2*$i + 1);
}
for my $i (1..$n)
{
print ' ' x $i;
say 'o' x (2*($n-$i) + 1);
}

Explanation

Let's go through the solution step by step:

  • Lines 26: We use ...