Copy Constructor and Recursion
Copy Constructor and Recursion
OOP
Copy Constructor
#include <iostream>
using namespace std;
class queue
{
int qval;
public:
void print();
int getval();
queue(int val)
{
setval(val);
}
Example …
void setval(int v)
{
qval = v;
}
};
int queue::getval()
{
return qval;
}
Example …
int main()
{
queue obj1(5);
queue obj2 = obj1;
obj1.setval(4);
cout << obj1.getval() << " " << obj2.getval() << " " << obj1.getval();
}
Output?
Recursion
• A piece that the function knows how to do and a piece that it does
not know how to do
• So it calls itself until it reaches the simplest part of problem.
• The recursion step often includes the keyword return
• The recursion step executes while the original call to the function is
still “open,” i.e., it has not yet finished executing.
• The recursion step can result in many more such recursive calls
• In continues for the recursion to eventually terminate
• Each time the function calls itself with a slightly simpler version of
the original problem
• This sequence of smaller and smaller problems must eventually
converge on the base case.
Factorial
#include <iostream>
using namespace std;
//Factorial function
int f(int n) {
if (n <= 1)
{
return 1;
}
else
{
return n * f(n - 1);
}
}
Example …
int main() {
int num;
cin >> num;
cout << "Factorial of entered number: " << f(num);
return 0;
}
Fibonacci Series
• 0, 1, 1, 2, 3, 5, 8, 13, 21, …
• begins with 0 and 1 and has the property that each subsequent
Fibonacci number is the sum of the previous two Fibonacci
numbers.
Fibonacci Example
#include <iostream>
using namespace std;
int fab(int n) {
{
if ((n == 0) || (n == 1)) // base cases
return n;
else // recursion step
return fab(n - 1) + fab(n - 2);
}
}
Example
int main() {
int num2;
cin >> num2;
cout << "Fibonacci at entered number is: " << fab(num2);
return 0;
}
Exponential Using Recursion
• Write a program that will take two inputs one no. as a base value
and other as power value and calculate exponential value of the
base no. on given exponent/power value.
Difference between Iteration and Recursion
• int i = 3;
• int *iPtr;
Or
int i, *iPtr;
Pointer Operators
• The & is a unary operator that returns the memory address of its
operand
• * is a unary operator that returns the value of the variable at the
address specified by its operand
• The second operator is *, and it is a complement/inverse of &.
Pointing different values
#include <iostream>
using namespace std;
int main() { int a, * aPtr;
a = 5;
aPtr = &a;
cout << "Adress of a " << &a; \\ 006FF9B8
cout << "Adress of a " << aPtr; \\ 006FF9B8
cout << "Adress of aPtr " << &aPtr; \\ 006FF9AC
cout << "value of aPtr" << aPtr; \\ 006FF9B
cout << "value of a" << a; \\ 5
cout << "value of a" << *(&a); \\ 5
cout << "value of a" << *aPtr; \\ 5
}
Pointers in Functions
• Write a program that will swap two int values in a functions using
pointers.