Q:

C# program to find the addition of two complex numbers

belongs to collection: C# Basic Programs | basics

0

C# program to find the addition of two complex numbers

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 C1C2 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

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to find the greatest common divisor (GC... >>
<< C# program to check given numbers are the pair of ...