Create a class 'COMPLEX' to hold a complex number. Write a friend function to add two complex numbers. Write a main function to add two COMPLEX objects.




Program Code:
#include<iostream.h>
#include<conio.h>
class complex
{
float real,imag;
public: void get_complex();
void show_complex();
friend complex add_complex(complex c1,complex c2);
};

void complex::get_complex()
{
cout<<"Enter real number :";
cin>> real;
cout<<"Enter Imaginary number :";
cin>>imag;
}
void complex::show_complex()
{
cout<<real<<"+i"<<imag;
}
complex add_complex(complex c1,complex c2)
{
complex c;
c.real=c1.real+c2.real;
c.imag=c1.imag+c2.imag;
return c;
}
int main()
{
clrscr();
complex c1,c2,c3;
c1.get_complex();
c2.get_complex();
c3=add_complex(c1,c2);
cout<<"\nComplex Number 1 = ";
c1.show_complex();
cout<<"\nComplex Number 2 = ";
c2.show_complex();
cout<<"\nSum of Complex Number 1 and 2 = ";
c3.show_complex();
getch();
return 0;
}




Output of the above program is:
Enter real number :12
Enter Imaginary number :10
Enter real number :3
Enter Imaginary number :5
Complex Number 1 = 12+i10
Complex Number 2 = 3+i5

Sum of Complex Number 1 and 2 = 15+i15





Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: