I think im getting dumber, why isnt this function finding the lowest?

i drank too much a couple of days ago, maybe i damaged my brain cos i still dont feel like i can think.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void find_lowest ( float arr [16])
{

    float retone=0;
    for (int Rpos = 0; Rpos<16; Rpos++)
    {
        for (int Cpos = 0; Cpos<16; Cpos++ )
        {
             if (arr[Rpos]>arr[Cpos])
             {
                 retone = arr[Cpos];
             }
        }
    }

    std::cout<<retone<<std::endl;
}
Last edited on
line 9 checks to see if R's entry is lower than C's
line 11 records C's entry (after you just confirmed it was the higher of the two)
Why reinvent the wheel when you could use std::min_element()?
http://cplusplus.com/reference/algorithm/min_element/

Anyway, what's the purpose of the second for() loop? That's what messes up the result.
The proper way, if you don't want to use the above function, is to use a single loop.

1
2
3
4
5
6
7
8
9
10
11
12
#include <algorithm>
#include <iostream>

void find_lowest(float arr[16])
{
    float r = arr[0];

    for (int i=0; i<16; ++i)
        r = std::min(r, arr[i]);

    std::cout << r << std::endl;
}

http://cplusplus.com/reference/algorithm/min/

I'd comment on the style, using int instead of std::size_t and C-style arrays instead of C++ containers, but it doesn't matter, am I right?
closed account (zb0S216C)
Why are you using two loops to transverse a single-dimension array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace Global
{
    unsigned int const ARRAY_SIZE( 16u );
}

float Lowest( float Array_[Global::ARRAY_SIZE] )
{
    float *Lowest_( &Array_[0] );
    for( int Index_( 1u ); Index_ < Global::ARRAY_SIZE; ++Index_ )
        if( *Lowest_ > Array_[Index_] )
            *Lowest_ = Array_[Index_];

    return( *Lowest_ );
}

Wazzak
The 2nd for loop is fine. He's just comparing each element to each other element, rather than simply comparing it to the current known lowest number.

Suboptimal, yes. But not wrong. The big problem with his original code is his assignment is backwards.


EDIT: Actually no.. you're right. That does screw it up! If you don't compare to the current lowest, you're not doing it right.

Whoops!
Last edited on
@ Framework: Index_ is supposed to be unsigned int, and your function kills the first element of the array because of the assignment in the if(), which you obviously wanted to be a pointer assignment instead.
yeah thanks guys these are all basics, some of which i didnt know about.

i didnt know about min element, should i just read the whole library?
how do you guys un-squiff your brains?

bout time i got the hang of template stuff too
Last edited on
Topic archived. No new replies allowed.