[try Beta version]
Not logged in

 
Bool Not Returning Value?

Mar 2, 2017 at 5:49am
Hey, so this is embarrassing since this is an incredibly basic function I'm trying to write, but whenever I test it I don't get either true or false. I need the function to check whether an array is in order from smallest to highest int. Same values next to each other should still return true, which is why I have <=. I've included a test. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool is_sorted(const int array[], int size) {
    for (int i = 0; i < size; i++) {
        if (array[i] <= array[i + 1]) {
            return true;
        }
    }
    return false;
}

void test_is_sorted() {
    const int array_a[5] = { 1, -2, 3, -4, 5 };
    int size_1 = 5;
    is_sorted(array_a, size_1);
}
Last edited on Mar 2, 2017 at 5:50am
Mar 2, 2017 at 6:01am
Hi,

You don't do anything with the value on line 13.
Mar 2, 2017 at 6:02am
removing my post, need checking
Last edited on Mar 2, 2017 at 6:04am
Mar 2, 2017 at 6:03am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <algorithm>

bool is_sorted( const int array[], std::size_t size ) {

    for( std::size_t i = 1 ; i < size; ++i ) {

        if( array[i] < array[i-1] ) return false ;
    }

    return true ;
}

void test_is_sorted() {

    const std::size_t size = 5;
    const int array_a[size] = { 1, -2, 3, -4, 5 };
    const int array_b[size] = { 1, 1, 3, 4, 5 };
    
    // http://en.cppreference.com/w/cpp/algorithm/is_sorted 
    if( is_sorted( array_a, size ) == std::is_sorted( array_a, array_a+size ) &&
        is_sorted( array_b, size ) == std::is_sorted( array_b, array_b+size ) )
    {
        std::cout << "ok\n" ;
    }

    else std::cout << "not ok\n" ;
}

int main () {

    test_is_sorted() ;

}
Mar 2, 2017 at 6:03am
whenever I test it I don't get either true or false


What do you mean by this exactly?
By looking at your tester function, I'd say your problem is that you assume that simply calling the function will print either "true" or "false". You'll have to store the result somewhere and print that, or print the returned value directly:

1
2
3
4
5
6
#include <iostream>

//...

bool result = is_sorted(array_a, size_1);
std::cout << std::boolalpha << result << std::endl;


1
2
3
4
5
#include <iostream>

//...

std::cout << std::boolalpha << is_sorted(array_a, size_1) << std::endl;
Topic archived. No new replies allowed.