Interview Questions

Write a function to output a diamond shape according to the given (odd) input.

Electrical Engineering Technical Interview Questions and Answers


(Continued from previous question...)

13. Write a function to output a diamond shape according to the given (odd) input.


   Examples:  Input is 5    Input is 7

                   *             *
                  ***           ***
                 *****         *****
                  ***         *******
                   *           *****
                                ***
                                 *

### BEGIN PERL SNIPET ###
for ($i = 1; $i <= (($input * 2) - 1); $i += 2) {
if ($i <= $input) {
$stars = $i;
$spaces = ($input - $stars) / 2;
while ($spaces--) { print " "; }
while ($stars--) { print "*"; }
} else {
$spaces = ($i - $input) / 2;
$stars = $input - ($spaces * 2);
while ($spaces--) { print " "; }
while ($stars--) { print "*"; }
}
print "\n";
}
### END PERL SNIPET ###

(Continued on next question...)

Other Interview Questions