In period 3 we learned what recursion was. We had to make a recursion at an application that used a sum inside a string and calculated it.
We could start with a string like “+1+2” as it would be easier. As addition we could try to add others like minus & multiply too. And try to remove the first +.
#include <iostream> #include <stdlib.h> #include <string.h> #include <math.h> int rekenen(int antw,int getal,char som[1]){ switch (som[0]){ case '-': return antw-getal; break; case '+': return antw+getal; break; case '/': return antw/getal; break; case ':': return antw/getal; break; case '*': return antw*getal; break; case 'x': return antw*getal; break; case '%': return antw%getal; break; case '^': return pow(antw,getal); break; default: return antw+getal; } } int getal_length(char som[]){ int i, r = 0; !isdigit(som[0])?i=1:i=0; while (1){ if (!isdigit(som[i]) || som[i]==0){ if(!isdigit(som[0])) return r+1; else return r; } r++; i++; } } int doeSom(char som[], int* antw, int beginning=0){ if (som[0]==0) return 1; int length = getal_length(som); char som2[length], newsom[] = " "; strncpy(som2,som,length); if (!isdigit(som[0])) *antw = rekenen(*antw,atoi(&som2[1]),som2); else if (beginning) *antw = *antw + atoi(&som[0]); strncpy(newsom,&som[length],40); doeSom(newsom,antw); } int main(){ using namespace std; int antw = 0; char som[] = "88+2:2"; doeSom(som,&antw,1); cout << som << " = " << antw << endl; cin.get(); return 1; }