c++ - Recursive function that takes the sum of odd integers -
the program runs spews out other stuff , not sure why. first output correct there not sure happens. here code:
#include <iostream> using namespace std; const int max = 10; int sum(int arraynum[], int n) { int total = 0; if (n <= 0) return 0; else for(int = 0; < max; ++) { if(arraynum[i] % 2 != 0) total += arraynum[i]; } cout << "sum of odd integers in array: " << total << endl; return arraynum[0] + sum(arraynum+1,n-1); } int main() { int x[max] = {13,14,8,7,45,89,22,18,6,10}; sum(x,max); system("pause"); return 0; }
the term recursion means (in simplest variation) solving problem reducing simpler version of same problem until becomes trivial. in example...
to compute num of odd values in array of n
elements have these cases:
- the array empty: result trivially 0
- the first element even: result sum of odd elements of rest of array
- the first element odd: result element added sum of odd elements of rest of array
in problem trivial case computing result empty array , simpler version of problem working on smaller array. important understand simpler version must "closer" trivial case recursion work.
once algorithm clear translation code simple:
// returns sums of odd numbers in // sequence of n elements pointed p int oddsum(int *p, int n) { if (n == 0) { // case 1 return 0; } else if (p[0] % 2 == 0) { // case 2 return oddsum(p + 1, n - 1); } else { // case 3 return p[0] + oddsum(p + 1, n - 1); } }
recursion powerful tool know , should try understand example until it's 100% clear how works. try starting rewriting scratch (i'm not saying should memorize it, try rewriting once read , think understood solution) , try solve small variations of problem.
no amount of reading can compensate writing code.
Comments
Post a Comment