Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Name – Aditya Gangurde
- Roll no -23
- Practical no 5
- Write a program in C++ to perform following operations on complex numbers
- Add, Subtract, Multiply, Divide. Use operator overloading for these
- operations. The objective of this assignment is to learn the concepts
- operator overloading.
- #include<iostream>
- using namespace std;
- class Complex{
- float real,img;
- public:
- void read();
- void display();
- Complex operator+(Complex);
- Complex operator-(Complex);
- Complex operator*(Complex);
- Complex operator/(Complex);
- };
- void Complex::read()
- {
- cout<<"Enter the real and imaginary values"<<endl;
- cin>>real>>img;
- }
- void Complex::display()
- {
- int val;
- if(img>0)
- cout<<real<<"+i"<<img;
- else{
- val = -img;
- cout<<real<<"-i"<<val;
- }
- }
- Complex Complex::operator+(Complex c2)
- {
- Complex sum;
- sum.real = real + c2.real;
- sum.img = img + c2.img;
- return sum;
- }
- Complex Complex::operator-(Complex c2)
- {
- Complex diff;
- diff.real = real - c2.real;
- diff.img = img - c2.img;
- return diff;
- }
- Complex Complex::operator*(Complex c2)
- {
- Complex mul;
- mul.real = (real * c2.real) - (img *c2.img);
- mul.img = (real * c2.img) + (img * c2.real);
- return mul;
- }
- Complex Complex::operator/(Complex c2)
- {
- Complex div;
- div.real = ((real * c2.real) + (img * c2.img)) / ((c2.real*c2.real)+(c2.img*c2.img));
- div.img = ((img * c2.real)- (real * c2.img)) / ((c2.real*c2.real)+(c2.img*c2.img));
- return div;
- }
- int main()
- {
- Complex c1,c2,res;
- c1.read();
- c2.read();
- res = c1+c2;
- cout<<"\n Result of addition ::"<<endl;
- res.display();
- res = c1-c2;
- cout<<"\n Result of subtraction ::"<<endl;
- res.display();
- res = c1*c2;
- cout<<"\n Result of multiplication ::"<<endl;
- res.display();
- res = c1/c2;
- cout<<"\n Result of divison ::"<<endl;
- res.display();
- }
- *****OUTPUT*****
- Enter the real and imaginary values
- 3
- 9
- Enter the real and imaginary values
- 2
- 7
- Result of addition ::
- 5+i16
- Result of subtraction ::
- 1+i2
- Result of multiplication ::
- -57+i39
- Result of divison ::
- 1.30189-i0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement