Search This Blog

program to perform basic arithemetic on two complex numbers using friend function

 ‪#‎include‬<iostream.h>  
 #include<stdlib.h>  
 #include<conio.h>  
 class complex  
 {  
 float a,b;  
 public:  
 complex()  
 {a=0.0;b=0.0;}  
 ~complex()  
 { }  
 friend complex operator +(complex,complex);  
 friend complex operator *(complex,complex);  
 friend complex operator /(complex,complex);  
 friend complex operator -(complex,complex);  
 void input()  
 {  
 cout<<"\n Enter real part: ";cin>>a;  
 cout<<"\n Enter imag. part: ";cin>>b;  
 }  
 void show()  
 {  
 cout<<"\n The complex number = ";  
 cout<<a<<"+("<<b<<")i"<<endl;  
 }  
 };  
 complex operator+(complex s,complex y)  
 {  
 complex x;  
 x.a=s.a+y.a;  
 x.b=s.b+y.b;  
 return x;  
 }  
 complex operator-(complex s,complex y)  
 {  
 complex x;  
 x.a=s.a-y.a;  
 x.b=s.b-y.b;  
 return x;  
 }  
 complex operator*(complex s,complex y)  
 {  
 complex x;  
 x.a=s.a*y.a-s.b*y.b;  
 x.b=s.a*y.b+s.b*y.a;  
 return x;  
 }  
 complex operator / (complex s,complex y)  
 {  
 complex x;  
 float p;  
 p=y.a*y.a+y.b*y.b;  
 x.a=(s.a*y.a+s.b*y.b)/p;  
 x.b=(s.b*y.a-s.a*y.b)/p;  
 return x;  
 }  
 void main()  
 {  
 char ch; int n;  
 complex c1,c2,c3,c4,c5,c6;  
 clrscr();  
 c1.input();  
 c2.input();  
 c1.show();  
 c2.show();  
 do{  
 cout<<"\n Enter operation symbol to perform \n any operation on given two complex numberslike (+,-,*,/):";  
 cout<<"\n Enter an option: ";  
 cin>>ch;  
 if(ch=='+')  
 n=1;  
 else if(ch=='-')  
 n=2;  
 else if(ch=='*')  
 n=3;  
 else if(ch=='/')  
 n=4;  
 else {  
 cout<<"\nwrong input\n";  
 exit(1);  
 }  
 switch(n) {  
 case 1: {  
 c3=c1+c2;  
 c3.show();  
 break; }  
 case 2: {  
 c4=c1-c2;  
 c4.show();  
 break; }  
 case 3:{  
 c5=c1*c2;  
 c5.show();  
 break; }  
 case 4: {  
 c6=c1/c2;  
 c6.show();  
 break; } }  
 cout<<"\n do you want to continue,y/n: ";  
 cin>>ch;  
 }while(ch!='n');  
 getch();  
 }  
   
OUTPUT:


No comments:

Post a Comment

leave a comment here