Skip to main content

Complex number multiplication using structure

Short answer

Product of (x1+iy1) and (x2+iy2): real = x1*x2 - y1*y2, imag = x1*y2 + y1*x2. For input 2 3 and 4 -1, the result is 11.00 + 10.00i.

Create a structure to hold any complex number x+iy. Write a program that uses the structure to read two complex numbers and display a third complex number which is the multiplication of the entered complex numbers.

For two complex numbers (x1 + i y1) and (x2 + i y2):

(x1 + i y1)(x2 + i y2) = (x1x2 − y1y2) + i (x1y2 + y1x2), since i² = −1.

The structure complex has two float members, x (real part) and y (imaginary part).

#include <stdio.h>

struct complex {
    float x;       /* real part */
    float y;       /* imaginary part */
};

int main(void)
{
    struct complex a, b, p;

    printf("Enter first complex number (x y): ");
    scanf("%f %f", &a.x, &a.y);
    printf("Enter second complex number (x y): ");
    scanf("%f %f", &b.x, &b.y);

    p.x = a.x * b.x - a.y * b.y;          /* (x1x2 - y1y2) */
    p.y = a.x * b.y + a.y * b.x;          /* (x1y2 + y1x2) */

    printf("Product = %.2f %c %.2fi\n", p.x, p.y < 0 ? '-' : '+', p.y < 0 ? -p.y : p.y);
    return 0;
}

Sample run (2 + 3i and 4 − i)

Input: 2 3 4 -1

Enter first complex number (x y): Enter second complex number (x y): Product = 11.00 + 10.00i

Check: (2)(4) − (3)(−1) = 11 and (2)(−1) + (3)(4) = 10, so the product is 11 + 10i.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 8 questions →