Cover Image for C++ program to add two complex numbers using class
100 views

C++ program to add two complex numbers using class

You can create a C++ program to add two complex numbers using a class to represent complex numbers. Here’s an example:

C++
#include <iostream>

class Complex {
private:
    double real;
    double imag;

public:
    Complex(double r, double i) : real(r), imag(i) {}

    Complex operator+(const Complex& other) {
        double resultReal = real + other.real;
        double resultImag = imag + other.imag;
        return Complex(resultReal, resultImag);
    }

    void display() {
        std::cout << "Complex number: " << real << " + " << imag << "i" << std::endl;
    }
};

int main() {
    // Create two complex numbers
    Complex num1(3.0, 4.0);
    Complex num2(1.5, 2.5);

    // Add the two complex numbers
    Complex sum = num1 + num2;

    // Display the result
    num1.display();
    num2.display();
    sum.display();

    return 0;
}

In this program:

  1. We define a Complex class to represent complex numbers. The class has two private data members: real and imag, which represent the real and imaginary parts of the complex number.
  2. The constructor Complex(double r, double i) initializes the complex number with the given real and imaginary parts.
  3. We overload the + operator using the operator+ member function to add two complex numbers. The result is a new complex number.
  4. The display member function is used to display the complex number.
  5. In the main function, we create two Complex objects (num1 and num2), initialize them with real and imaginary parts, and then add them together using the + operator. Finally, we display the original complex numbers and the result.

When you run this program, it will create two complex numbers, add them, and display the result:

Complex number: 3 + 4i
Complex number: 1.5 + 2.5i
Complex number: 4.5 + 6.5i

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS