# Re: obj 8-2

Discussion in 'Perl Misc' started by Rainer Weikusat, Feb 21, 2014.

1. ### Rainer WeikusatGuest

Marek Novotny <> writes:
> #!/usr/bin/perl
> # File: obj8-2.pl
> # Use loops and if statements to find the greatest number in the array.
> # Once you determine this number be sure to print it out.
> # Use comments to explain every line of your code:
>
> @array = (42,41,42,31,54,42,56,57,46,58,59,60,34,61);
>
> \$a = 0;
> \$b = 1;
> \$i = 0;
>
> while (\$i < (\$#array * 2)){
> if ((\$array[\$a]) >= (\$array[\$b])){
> \$c = (\$array[\$a]);
> \$b++;
> }else{
> if ((\$array[\$b]) >= (\$array[\$a])){
> \$c = (\$array[\$b]);
> \$a++;
> }
> }
> \$i++;
> }
> print "The Answer is: \$c\n";

Additional remark: This is broken, cf

--------------
@array = (-1, -2);

\$a = 0;
\$b = 1;
\$i = 0;

while (\$i < (\$#array * 2)){
print("\$c\n");

if ((\$array[\$a]) >= (\$array[\$b])){
\$c = (\$array[\$a]);
\$b++;
}else{
if ((\$array[\$b]) >= (\$array[\$a])){
\$c = (\$array[\$b]);
\$a++;
}
}
\$i++;
}
print "The Answer is: \$c\n";
------------------

What happens here is that \$b runs over the end of the array and the
value of elements of @array beyond \$array[1] is undef. That's no problem
if all real elements have values >= 0 because undef is equivalent to 0
when used in a numerical operation. But if the largest value in the
array is smaller than 0, undef will compare greater.

Rainer Weikusat, Feb 21, 2014