The source code to demonstrate the addition of two complex numbers is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# Program to add complex numbers
using System;
class Complex
{
public int real;
public int img;
public Complex()
{
this.real = 0;
this.img = 0;
}
public Complex(int real, int img)
{
this.real = real;
this.img = img;
}
public static Complex operator +(Complex Ob1, Complex Ob2)
{
Complex temp = new Complex();
temp.real = Ob1.real + Ob2.real ;
temp.img = Ob1.img + Ob2.img ;
return temp;
}
public void PrintComplexNumber()
{
Console.WriteLine("{0} + {1}i", real, img);
}
}
class Program
{
static void Main()
{
Complex C1 = new Complex(5, 6);
Complex C2 = new Complex(7, 3);
Complex C3;
C3 = C1 + C2;
Console.Write("C1 : ");
C1.PrintComplexNumber();
Console.Write("C2 : ");
C2.PrintComplexNumber();
Console.Write("C3 : ");
C3.PrintComplexNumber();
}
}
Here we overload the binary '+' operator to add two complex numbers, and we also defined a method PrintComplexNumber() to print a complex number on the console screen.
In the Main() method, we created two objects of complex class C1, C2 initialized using parameterized constructor and we created a reference C3.
C3 = C1 + C2;
Here, we assign the sum of C1 and C2 into C3 and then we printed values of all objects.
Program:
The source code to demonstrate the addition of two complex numbers is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
Here, we created a class Complex that contains data members real and img. Here we defined two constructors two initialize the values of data members.
public static Complex operator +(Complex Ob1, Complex Ob2) { Complex temp = new Complex(); temp.real = Ob1.real + Ob2.real ; temp.img = Ob1.img + Ob2.img ; return temp; }Here we overload the binary '+' operator to add two complex numbers, and we also defined a method PrintComplexNumber() to print a complex number on the console screen.
In the Main() method, we created two objects of complex class C1, C2 initialized using parameterized constructor and we created a reference C3.
C3 = C1 + C2;
Here, we assign the sum of C1 and C2 into C3 and then we printed values of all objects.
need an explanation for this answer? contact us directly to get an explanation for this answer