Re: obj 8-2

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

  1. 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
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mark Kamoski
    Replies:
    3
    Views:
    15,747
    Jay B. Harlow [MVP - Outlook]
    Aug 9, 2003
  2. Phil Endecott

    Obj* ptr = new Obj(X)

    Phil Endecott, Jun 3, 2005, in forum: C++
    Replies:
    5
    Views:
    472
    Mark P
    Jun 3, 2005
  3. Shalabh Chaturvedi
    Replies:
    2
    Views:
    447
    Mike C. Fletcher
    Feb 20, 2004
  4. Matthew Thorley

    How do you convert a string obj to a file obj?

    Matthew Thorley, May 4, 2005, in forum: Python
    Replies:
    7
    Views:
    511
    Peter Otten
    May 4, 2005
  5. alf
    Replies:
    9
    Views:
    414
Loading...

Share This Page