0

This is a recursive function I did to find out if the given digits in a number are in a decreasing order, I'm sure my base is correct as I see the function does return false for the first few digits, but because the last two are in a decreasing order the function returns true in the end.

I can't figure out how to keep that false value and return it back to the original call for the function.

#include<iostream>
using namespace std;
bool dec(int n);

void main()
{
    cout << dec(1231);
}

bool dec(int n)
{
    bool res;

    if (n < 10)
        return true;
    else
    {
        res = dec(n / 10);
        if ((n / 10) % 10 > n % 10)
            return true;
        else
            return false;
    }
}
6
  • 3
    You aren't using res at all. You're just assigning to it. Commented Dec 10, 2014 at 16:37
  • if (x) { return true; } else { return false; } is kind of an anti-pattern. Why not just return x;? Commented Dec 10, 2014 at 16:42
  • @cdhowie it doesn't work when I change it to return res. Commented Dec 10, 2014 at 16:44
  • @kuhaku Not return res, but the whole expression. For example, as per @b4hand's answer: return res && (n / 10) % 10 > n % 10; Commented Dec 10, 2014 at 16:45
  • @cdhowie I didn't know it could be done without the if else. Commented Dec 10, 2014 at 16:50

1 Answer 1

1

You should only return true if res is also true. Try

return (res && (n / 10) % 10 > n % 10);
Sign up to request clarification or add additional context in comments.

1 Comment

I thought about that but didn't believe it would work because of the recursion, but it does. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.