C# program to find the addition of two complex numbers

Here, we are going to learn how to find the addition of two complex numbers in C#?
Submitted by Nidhi, on September 21, 2020

Here we will demonstrate the addition of two complex numbers. The complex number contains two parts real and imaginary.

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.

//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();
    }
}

Output:

C1 : 5 + 6i
C2 : 7 + 3i
C3 : 12 + 9i
Press any key to continue . . .

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.