C Program – Add Two Complex Numbers - Struct & Separate Parts

Add Complex Numbers Using a Struct

#include <stdio.h>
typedef struct {
    float real;
    float imag;
} Complex;
int main() {
    Complex a, b, sum;
    printf("Enter real and imaginary parts of first complex number: ");
    scanf("%f %f", &a.real, &a.imag);
    printf("Enter real and imaginary parts of second complex number: ");
    scanf("%f %f", &b.real, &b.imag);
    sum.real = a.real + b.real;
    sum.imag = a.imag + b.imag;
    printf("Sum = %.1f + %.1fi\n", sum.real, sum.imag);
    return 0;
}
Enter real and imaginary parts of first complex number: 3 2
Enter real and imaginary parts of second complex number: 1 7
Sum = 4.0 + 9.0i
        

This approach defines a struct to group the real and imaginary parts together. After reading both complex numbers, their respective parts are added and printed in standard form.

Add Complex Numbers Using Separate Variables

#include <stdio.h>
int main() {
    float real1, imag1, real2, imag2, realSum, imagSum;
    printf("Enter real and imaginary parts of first complex number: ");
    scanf("%f %f", &real1, &imag1);
    printf("Enter real and imaginary parts of second complex number: ");
    scanf("%f %f", &real2, &imag2);
    realSum = real1 + real2;
    imagSum = imag1 + imag2;
    printf("Sum = %.1f + %.1fi\n", realSum, imagSum);
    return 0;
}
Enter real and imaginary parts of first complex number: 2 5
Enter real and imaginary parts of second complex number: 4 3
Sum = 6.0 + 8.0i
        

Instead of using a structure, this method handles each part individually. It works by storing and adding real parts separately from imaginary parts before displaying the combined result.

Sai Kishore Randhi, author
About the author

Sai Kishore Randhi

Embedded systems, VLSI, and chip design

Sai Kishore writes about embedded systems, VLSI, chip design, and the programming concepts behind modern hardware.

View LinkedIn profile ↗