As many have said, this problem is clearly best solved wit a loop.
However...as an
intellectual exercise:
Yes, you could do it with recursion:
Recursion - Wikipedia, the free encyclopedia[
^]
#include <iostream>
using namespace std;
bool numCheck(int num);
typedef bool(*CheckFn)(int);
int enterCorrectNumber(CheckFn);
int main(){
enterCorrectNumber(&numCheck);
}
bool numCheck(int num){
return (num == 10);
}
int enterCorrectNumber(CheckFn checker){
int input;
cout << "Enter in a number : ";
cin >> input;
if (checker(input)){
cout << "Correct!" << endl;
return input;
}
cout << "Wrong!" << endl;
return enterCorrectNumber(checker);
}
You must be careful to use this only when you can bound the number of times the function can call itself or else a stack overflow will occur!
This example is structured in a way called
tail-recursion so an optimizing compiler can generate the code in such a way as to prevent the stack overflow from ever happening.