C++ - Program - Add 2 Complex Numbers

#include <iostream>
// Structure to represent a complex number
struct Complex {
    double real;
    double imaginary;
};
// Function to add two complex numbers
Complex addComplexNumbers(Complex num1, Complex num2) {
    Complex sum;
    sum.real = num1.real + num2.real;
    sum.imaginary = num1.imaginary + num2.imaginary;
    return sum;
}
// Function to display a complex number
void displayComplexNumber(Complex num) {
    std::cout << num.real << " + " << num.imaginary << "i" << std::endl;
}
int main() {
    Complex num1, num2;
    std::cout << "Enter the real and imaginary parts of the first complex number: ";
    std::cin >> num1.real >> num1.imaginary;
    std::cout << "Enter the real and imaginary parts of the second complex number: ";
    std::cin >> num2.real >> num2.imaginary;
    // Add the complex numbers
    Complex sum = addComplexNumbers(num1, num2);
    // Display the result
    std::cout << "Sum of the complex numbers: ";
    displayComplexNumber(sum);
    return 0;
}

In this program, we use a struct called Complex to represent a complex number. The Complex struct has two members: real for the real part and imaginary for the imaginary part of the complex number.

We define a function addComplexNumbers that takes two complex numbers (num1 and num2) as input and returns their sum as a new complex number. The function creates a Complex struct called sum and assigns the sum of the corresponding real and imaginary parts of the input complex numbers to sum.real and sum.imaginary, respectively. It then returns sum.

The displayComplexNumber function takes a complex number (num) as input and displays it on the console in the format real + imaginary i.

In the main function, we prompt the user to enter the real and imaginary parts of two complex numbers (num1 and num2). The input is stored in the respective members of the Complex structs. We then call the addComplexNumbers function to add the complex numbers and store the result in a Complex struct called sum. Finally, we display the sum using the displayComplexNumber function.