C++ program to perform arithmetic operations of two complex numbers using operator overloading
by Ranjith | March 13th, 2010.BINARY OPERATOR
AIM:
A program to perform simple arithmetic operations of two complex numbers using operator overloading.
ALGORITHAM:
• Start the process
• Get the complex value a.real and a.image
• Check while ((ch=getchar())!=’q’)
o True : execute switch(ch)
o Case ‘a’:Then
Compute c<-a+b, Print c.real and c.imag
o Case ‘s’: Then
Compute c<-a-b, Print c.real and c.imag
o Case ‘m’: Then
Compute c<-a*b, Print c.real and c.imag
o Case ‘d’: Then
Compute c<-a/b, Print c.real and c.imag
o End of switch
• End of while
• Stop the process
PROGRAM
#include<iostream.h> #include<conio.h> #include<string.h> struct complex { float real; float imag; }; complex operator + (complex a,complex b); complex operator - (complex a,complex b); complex operator * (complex a,complex b); complex operator / (complex a,complex b); void main() { complex a,b,c; int ch; void menu(void);clrscr(); cout<<"Enter the first complex no:"; cin>>a.real>>a.imag; cout<<"Enter the second complex no:"; cin>>b.real>>b.imag; menu(); while ((ch = getchar()) != 'q') { switch(ch) { case 'a':c =a + b; cout<<"Addition of 2 no’s"; cout<<c.real<<"+i"<<c.imag; break; case 's':c=a-b; cout<<"Substraction of 2 no’s"; cout<<c.real<<"i"<<c.imag; break; case 'm':c=a*b; cout<<"Multiplication of 2 no’s"; cout<<c.real<<"i"<<c.imag; break; case 'd':c=a/b; cout<<"Division of 2 no’s"; cout<<c.real<<"i"<<c.imag; break; } } } void menu() { cout<<"complex no: operators"; cout<<"a->addition"; cout<<"s->substraction"; cout<<"m->multiplication"; cout<<"d->division"; cout<<"q->quit"; cout<<"options please"; } complex operator -(struct complex a, struct complex b) { complex c; c.real=a.real-b.real; c.imag=a.imag-b.imag; return(c); } complex operator *(struct complex a, struct complex b) { complex c; c.real=((a.real*b.real)-(a.imag*b.imag)); c.imag=((a.real*b.imag)+(a.imag*b.real)); return(c); } complex operator +(struct complex a,struct complex b) { complex c; c.real=a.real+b.real; c.imag=a.imag+b.imag; return(c); } complex operator /(struct complex a, struct complex b) { complex c; float temp; temp=((b.real*b.real)+(b.imag*b.imag)); c.real=((a.real*b.real)+(a.imag*b.imag))/temp; return(c); }
OUTPUT
Enter the first complex no: 1,1
Enter the second complex no: 2,2
Addition of 2 no’s : 3+I3
Share and Enjoy:



















