The goal of this project is to practice recursion. The Adder class performs the
ID: 3790545 • Letter: T
Question
The goal of this project is to practice recursion. The Adder class performs the mathematical operation a + b in two ways: iterative (using loops or control flow); recursive (calls itself over and over again). You might not think that addition could be implemented recursively, but if you follow the cases shown below, you will see that it can be:
BASE CASE: if ( a == 0 ) return( b );
BASE CASE: if ( b == 0 ) return( a );
RECURSIVE CASE: else return (RecursiveAPlusB( a - 1, b - 1 ) + 2 );
HINT: You may add additional methods to the Adder class as long as you implement those defined in the original class definition.
Implementation Details
Sample Driver
Adder
Adder( int a, int b );
int getA( ) const;
int getB( ) const;
int RecursiveAPlusB( ) const;
int IterativeAPlusB( ) const;
int myValueofA;
int myValueofB;
Adder ten( 6, 4 );
// All these calls should produce the
// exact same answer...
// namely, the number 10!
cout << ten.RecursiveAPlusB( ) << endl;
cout << ten.IterativeAPlusB( ) << endl;
cout << ten.RecursiveAPlusB( ) << endl;
Adder tenagain( 2, 8 );
cout << tenagain.RecursiveAPlusB( ) << endl;
cout << tenagain.IterativeAPlusB( ) << endl;
cout << tenagain.RecursiveAPlusB( ) << endl;
Implementation Details
Sample Driver
Adder
Adder( int a, int b );
int getA( ) const;
int getB( ) const;
int RecursiveAPlusB( ) const;
int IterativeAPlusB( ) const;
int myValueofA;
int myValueofB;
Adder ten( 6, 4 );
// All these calls should produce the
// exact same answer...
// namely, the number 10!
cout << ten.RecursiveAPlusB( ) << endl;
cout << ten.IterativeAPlusB( ) << endl;
cout << ten.RecursiveAPlusB( ) << endl;
Adder tenagain( 2, 8 );
cout << tenagain.RecursiveAPlusB( ) << endl;
cout << tenagain.IterativeAPlusB( ) << endl;
cout << tenagain.RecursiveAPlusB( ) << endl;
Explanation / Answer
#include<iostream>
using namespace std;
class Adder { int myValueofA;
int myValueofB;
mutable int A, B; //A and B are mutable public :
//Constructor for initialization Adder( int a, int b ) { myValueofA=a;
myValueofB=b; A=a; B=b; }
Adder( int a, int b );
int getA( ) const;
int getB( ) const;
int RecursiveAPlusB( ) const;
int IterativeAPlusB( ) const;
// exact same answer...
// namely, the number 10!
cout << ten.RecursiveAPlusB( ) << endl;
cout << ten.IterativeAPlusB( ) << endl;
cout << ten.RecursiveAPlusB( ) << endl;
Adder tenagain( 2, 8 );
cout count;
end}}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.