C PROGRAMMING PROGRAM • STRUCTURES, UNIONS & ENUMS

Add Two Complex Numbers Using Structures

Learn how to add two complex numbers using structures using a clear C program.

IntermediatestructComplex numbersFunction return

PROBLEM UNDERSTANDING

Input and expected output

Sample input
3 4
5 -2
Sample output
Sum = 8.00 + 2.00i

COMPLETE C PROGRAM

Complete C implementation

add-complex-numbers-structure.c
Open in compiler
#include <stdio.h>

struct Complex
{
    double real;
    double imaginary;
};

struct Complex add(struct Complex first, struct Complex second)
{
    struct Complex result = {first.real + second.real, first.imaginary + second.imaginary};
    return result;
}

int main(void)
{
    struct Complex first, second, result;

    printf("Enter real and imaginary parts of first number: ");
    scanf("%lf %lf", &first.real, &first.imaginary);
    printf("Enter real and imaginary parts of second number: ");
    scanf("%lf %lf", &second.real, &second.imaginary);
    result = add(first, second);
    printf("Sum = %.2f %c %.2fi\n", result.real,
           result.imaginary < 0 ? '-' : '+', result.imaginary < 0 ? -result.imaginary : result.imaginary);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Sum = 8.00 + 2.00i
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Add corresponding real and imaginary members and return the result structure.
  3. Display the computed result.

Add corresponding real and imaginary members and return the result structure.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.