In this tutorial you will learn about the C++ Program to Subtract Complex Number Using Operator Overloading and its application with practical example.
C++ Program to Subtract Complex Number Using Operator Overloading
In this tutorial, we will learn to create a C++ program that will Subtract Complex Number Using Operator Overloading in C++ programming.
Prerequisites.
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- While loop in C++ programming.
What is a Complex Number?
A number is said to be a complex number if it is in the form of x+yi, where x and y are real numbers, and i is an indeterminate satisfying the condition i2 = −1.
For example, 2 + 3i
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declare the variables for the program. 2. Taking the input numbers and exponential number by the user. 3. Calculating the complex number. 4. Print the Result. 5. End the program. |
Program to Subtract Complex Number Using Operator Overloading:-
In this program, we will subtract a Complex Number Using Operator Overloading. First, we will take the numbers input from the user and second, we will solve that number using operator overloading.
Program:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
#include <iostream> using namespace std; class Complex{ public: float real; float img; Complex(){ this->real = 0.0; this->img = 0.0; } Complex(float real, float img){ this->real = real; this->img = img; } //overloading + operator Complex operator+(const Complex &obj){ Complex temp; temp.img = this->img + obj.img; temp.real = this->real + obj.real; return temp; } //overloading - operator Complex operator-(const Complex &obj){ Complex temp; temp.img = this->img - obj.img; temp.real = this->real - obj.real; return temp; } void display(){ cout << this->real << " + " << this->img << "i" << endl; } }; int main() { //Declaring the required variables for the program Complex a, b, c; //taking input number 1 cout << "Enter real and complex coefficient of the first complex number: " << endl; cin >> a.real; cin >> a.img; //taking input number 2 cout << "Enter real and complex coefficient of the second complex number: " << endl; cin >> b.real; cin >> b.img; //printing teh output for the program cout << "Addition Result: "; c = a+b; c.display(); cout << "Subtraction Result: "; c = a-b; c.display(); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- a = it will hold the complex value.
- b = it will hold the complex value.
- c = it will hold the complex value.
- temp = it will hold the complex value.
- real = it will hold the float value.
- img = it will hold the integer value.
Taking the input integer number and exponent from the user.