Greatest element of a list

From Rosetta Code
Revision as of 07:47, 1 June 2008 by MikeMol (talk | contribs) (Created task)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Greatest element of a list
You are encouraged to solve this task according to the task description, using any language you may know.

Create a function that returns the maximum value in a provided set of values, where the number of values isn't known until runtime.

C

This works well with floats. Replace with double, int or what-have-you before passing a different data type. <C>function max(unsigned int count, float values[] {

    float themax;
    for(unsigned int idx = 0; idx < count; ++idx) {
         themax = values[idx] > themax ? values[idx] : themax;
    }
    return themax;

}</C>

C++

This will work for any type with a > operator defined. <cpp>template<typename Ty> Ty max(unsigned int count, Ty values[]) {

    Ty themax;
    for(unsigned int idx = 0; idx <; count; ++idx) {
         themax = values[idx] > themax ? values[idx] : themax;
    }
    return themax;

}</cpp>

Perl

<perl>sub max {

    my $list = \@_;
    my $themax = $list->[0];
    foreach ( @$list ) {
         $themax = $_ > $themax ? $_ : $themax;
    }
    return $themax;

}</perl>