Advertisement
adiee

Untitled

Jun 3rd, 2021
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. Name – Aditya Gangurde
  2. Roll no -23
  3. Practical no 5
  4.  
  5. Write a program in C++ to perform following operations on complex numbers
  6. Add, Subtract, Multiply, Divide. Use operator overloading for these
  7. operations. The objective of this assignment is to learn the concepts
  8. operator overloading.
  9.  
  10.  
  11.  
  12. #include<iostream>
  13. using namespace std;
  14.  
  15. class Complex{
  16. float real,img;
  17. public:
  18. void read();
  19. void display();
  20. Complex operator+(Complex);
  21. Complex operator-(Complex);
  22. Complex operator*(Complex);
  23. Complex operator/(Complex);
  24.  
  25. };
  26.  
  27.  
  28. void Complex::read()
  29. {
  30. cout<<"Enter the real and imaginary values"<<endl;
  31. cin>>real>>img;
  32. }
  33.  
  34.  
  35. void Complex::display()
  36. {
  37. int val;
  38. if(img>0)
  39. cout<<real<<"+i"<<img;
  40. else{
  41.  
  42. val = -img;
  43. cout<<real<<"-i"<<val;
  44. }
  45. }
  46.  
  47. Complex Complex::operator+(Complex c2)
  48. {
  49. Complex sum;
  50. sum.real = real + c2.real;
  51. sum.img = img + c2.img;
  52. return sum;
  53. }
  54. Complex Complex::operator-(Complex c2)
  55. {
  56. Complex diff;
  57. diff.real = real - c2.real;
  58. diff.img = img - c2.img;
  59. return diff;
  60. }
  61.  
  62. Complex Complex::operator*(Complex c2)
  63. {
  64. Complex mul;
  65. mul.real = (real * c2.real) - (img *c2.img);
  66. mul.img = (real * c2.img) + (img * c2.real);
  67.  
  68. return mul;
  69. }
  70.  
  71.  
  72. Complex Complex::operator/(Complex c2)
  73. {
  74. Complex div;
  75. div.real = ((real * c2.real) + (img * c2.img)) / ((c2.real*c2.real)+(c2.img*c2.img));
  76. div.img = ((img * c2.real)- (real * c2.img)) / ((c2.real*c2.real)+(c2.img*c2.img));
  77. return div;
  78. }
  79.  
  80.  
  81. int main()
  82. {
  83. Complex c1,c2,res;
  84. c1.read();
  85. c2.read();
  86. res = c1+c2;
  87. cout<<"\n Result of addition ::"<<endl;
  88. res.display();
  89.  
  90. res = c1-c2;
  91. cout<<"\n Result of subtraction ::"<<endl;
  92. res.display();
  93.  
  94.  
  95. res = c1*c2;
  96. cout<<"\n Result of multiplication ::"<<endl;
  97. res.display();
  98.  
  99. res = c1/c2;
  100. cout<<"\n Result of divison ::"<<endl;
  101. res.display();
  102.  
  103. }
  104.  
  105.  
  106.  
  107. *****OUTPUT*****
  108.  
  109. Enter the real and imaginary values
  110. 3
  111. 9
  112. Enter the real and imaginary values
  113. 2
  114. 7
  115.  
  116. Result of addition ::
  117. 5+i16
  118. Result of subtraction ::
  119. 1+i2
  120. Result of multiplication ::
  121. -57+i39
  122. Result of divison ::
  123. 1.30189-i0
  124.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement