c++ - Recursively return if statement calls -
i'm trying design program takes integer array input, , returns combinations of values add predetermined sum. sake of clarity, recursive function return true when total adds 10.
however, want return values array comprise of total, definition follows;
if suminarray returns true, print each number array.
my hope was, once base clause reached, recursion unwind, , if
statements evaluated, , each value printed if
statement. however, printed last value array made target total, not values preceded it.
i've misunderstood recursive behaviour of c++. know how work recursive return calls, logically, if if
statement can't evaluated until recursive function returns true
or false
, shouldn't unwind, also?
#include <iostream> bool suminarray(int *numbers, const int &size, int startpos, int total); using namespace std; int main() { int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int startpos = 0; int total = 0; suminarray(numbers, 10, 0, total); return 0; } bool suminarray(int *numbers, const int &size, int startpos, int total) { if(total == 10) { cout << "result. " << endl; return true; } else if(total > 10) { return false; } else { for(int = startpos; < size; i++) { cout << " loop " << << endl; cout << " total" << total << endl; if(suminarray(numbers, size, i+1, total+numbers[i]) == true) { cout << "uses " << numbers[i] << endl; } } } }
edit: correction source code.
the immediate problem (which compiler should warning about), have no return statement in final else
block, causes function fall off end without returning either true
or false
, leading undefined behavior. if fix in obvious way:
else { for(int = startpos; < size; i++) { cout << " loop " << << endl; cout << " total" << total << endl; if(suminarray(numbers, size, i, total+numbers[i]) == true) { cout << "uses " << numbers[i] << endl; return true; } } return false; }
your program works, prints first set of values add 10 finds.
that shows problem approach -- each function call can return once -- can't (easily) have both return success , continue try more alternatives.
Comments
Post a Comment