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#? By Nidhi Last updated : April 15, 2023

Adding Two Complex Numbers

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

C# code for adding two complex numbers

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.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.