2.5 KiB
2.5 KiB
- Write a program to enter any number and find its factorial using constructor.
- Write a program to perform addition of two complex numbers using constructor overloading. The first constructor which takes no argument is used to create objects which are not initialized, second which takes one argument is used to initialize real and imag parts to equal values and third which takes two arguments is used to initialize real and imag to two different values.
- Write a program to generate a Fibonacci series using a copy constructor.
Write a program to enter any number and find its factorial using constructor.
#include <cstdint>
#include <iostream>
using namespace std;
uint64_t factorial(uint n) { return (n ? n * factorial(n - 1) : 1); }
class NumberWithFactorial {
private:
uint n;
uint64_t f;
public:
NumberWithFactorial(uint);
};
NumberWithFactorial::NumberWithFactorial(uint n) {
this->n = n;
this->f = factorial(n);
cout << "Factorial of " << this->n << " is " << this->f << endl;
}
int main() {
NumberWithFactorial(5);
}
Write a program to perform addition of two complex numbers using constructor overloading. The first constructor which takes no argument is used to create objects which are not initialized, second which takes one argument is used to initialize real and imag parts to equal values and third which takes two arguments is used to initialize real and imag to two different values.
#include <iostream>
using namespace std;
class Complex {
private:
int r, i;
public:
Complex() = default;
Complex(int);
Complex(int, int);
Complex operator+(Complex);
void display();
};
Complex::Complex(int a) { this->r = this->i = a; }
Complex::Complex(int r, int i) {
this->r = r;
this->i = i;
}
Complex Complex::operator+(Complex op) {
return Complex(this->r + op.r, this->i + op.i);
}
void Complex::display() {
if (this->r)
cout << this->r;
if (this-> r && this->i > 0)
cout << '+';
if (this->i)
cout << this->i << 'i';
cout << endl;
}
int main() {
Complex c;
Complex a(4), b(34, -2124);
c = a + b;
c.display();
}
Write a program to generate a Fibonacci series using a copy constructor.
#include <iostream>
using namespace std;
class Fibo {
private:
uint lim;
public:
Fibo() = default;
Fibo(uint);
Fibo(const Fibo &);
};
Fibo::Fibo(uint n) { this->lim = n; }
Fibo::Fibo(const Fibo &f) {
uint a = 0, b = 1, i;
cout << a << ' ' << b;
for (i = 0; i < f.lim - 2; i++) {
cout << ' ' << a + b;
b += a;
a = b - a;
}
cout << endl;
}
int main() {
Fibo a(10);
Fibo b = a;
}