1
\$\begingroup\$

This works just fine, however, the assignment was to write a recursive "function". I'm curious to see if this should count.

Any comments / suggestions/ stuff I should watch out for are appreciated.

#include <iostream>
#include <functional>
#include <cctype>
#include <cstdlib>

int main() {

    char go_again = 'Y';

    do {

        int lhs, rhs;
        std::cout << "Enter 2 integer values: ";
        std::cin >> lhs >> rhs;

        if (lhs < 0 || rhs < 0)
            std::cout << "Implicit converstion to positive integers.\n";

        std::function<int(int, int)> 
            gcd = [&](int lhs, int rhs) -> int { 
                return rhs == 0 ? std::abs(lhs) : gcd(rhs, lhs % rhs); 
        };

        std::cout << "gcd == " << gcd(lhs, rhs) << '\n';
        std::cout << "Go again? <Y/N> ";
        std::cin >> go_again;

    } while (std::toupper(go_again) == 'Y');

}
\$\endgroup\$
0
2
\$\begingroup\$

Not that familiar with C++, but that certainly looks like recursion to me...

The variable gcd contains a function, which then calls itself. The very definition of recursion.

But I would ask what you gain by not making it a regular function?

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.