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');
}
asked Oct 26, 2013 at 5:53
\$\endgroup\$
0

1 Answer 1

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?

answered Oct 26, 2013 at 6:18
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.