Skip to main content

Complex number sum via functions

Write a program to represent complex number by a structure with real and imaginary as members. Take 2 complex numbers as input from user into structure variables. Pass the complex numbers to a function which calculates sum and returns it. Display the sum from another function display().

Design.

  • The structure complex has real and imag members.
  • main() reads two complex numbers into the structure variables c1 and c2.
  • add() takes the two structures (by value), adds the real and imaginary parts separately, and returns the sum as a structure.
  • display() receives the sum and prints it in the form a + bi.
#include <stdio.h>

struct complex {
    float real;
    float imag;
};

struct complex add(struct complex a, struct complex b)
{
    struct complex s;
    s.real = a.real + b.real;
    s.imag = a.imag + b.imag;
    return s;
}

void display(struct complex c)
{
    printf("Sum = %.1f %c %.1fi\n", c.real, c.imag < 0 ? '-' : '+',
           c.imag < 0 ? -c.imag : c.imag);
}

int main(void)
{
    struct complex c1, c2, sum;
    printf("Enter first complex number (real imaginary): ");
    scanf("%f %f", &c1.real, &c1.imag);
    printf("Enter second complex number (real imaginary): ");
    scanf("%f %f", &c2.real, &c2.imag);
    sum = add(c1, c2);
    display(sum);
    return 0;
}

Sample run (3 + 4i and 1.5 − 6i)

Input: 3 4 1.5 -6

Enter first complex number (real imaginary): Enter second complex number (real imaginary): Sum = 4.5 - 2.0i

(3 + 1.5) + (4 − 6)i = 4.5 − 2i.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 8 questions →