Structure Assignment 22 — Create a Structure to Represent a Complex Number
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Create a Structure to Represent a Complex Number (Real, Imaginary)

📑 On this page:
  • The number that needs two floats
  • What a complex number really is
  • The struct and its fields
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions

The number that needs two floats

Here's a number: 3 + 4i. What type would you use to store it in C? It's not an int because 3 and 4 are separate parts. It's not a float because a float holds one number, not a pair. And it's not an array because the two parts have different meanings — one is the real part, the other is the imaginary part. You can't mix them up.

A struct is exactly what you need. Two floats, named real and imag, grouped into a single type. That's a complex number: a pair of values that always travel together. And once you have that, all the standard complex-number operations — addition, subtraction, multiplication, magnitude — become small functions that operate on the two parts.

This assignment is just about setting up the struct and printing the number in the familiar a + bi form. That's a smaller step than you might expect, but the printing has a small wrinkle: when the imaginary part is negative, you want to print "3.00 - 4.00i", not "3.00 + -4.00i". Getting that right is the interesting part of the exercise.

What a complex number really is

In mathematics, a complex number has the form a + bi, where a is the real part, b is the imaginary part, and i is the imaginary unit defined as √(-1). So 3 + 4i has real part 3 and imaginary part 4. And 3 − 4i has real part 3 and imaginary part −4. The imaginary part can be negative, positive, or zero.

What makes complex numbers interesting is that they're closed under arithmetic: add two complex numbers, you get a complex number. Multiply two, you get a complex number. Divide, take square roots, exponentiate — you can do all of it, and the result is always another complex number. This is why they show up all over engineering: signal processing, control theory, electrical circuits, quantum mechanics. Whenever the math involves oscillations, rotations, or waves, complex numbers make it simpler.

In C, we represent them as a struct with two floats. The real field holds the real part; the imag field holds the imaginary part. That's the whole data model. The interesting work is in what you do with the two fields — addition, subtraction, and so on. For this assignment, we just want to set up the struct and print one complex number cleanly.

💡 In one line: struct complex { float real; float imag; }; is the type. struct complex c = {3.0f, 4.0f}; is 3 + 4i. Print with the right sign in the middle — + if imag ≥ 0, - if imag < 0.

A complex number 3 + 4i drawn on the complex plane: real axis horizontal, imaginary axis vertical, with the point at (3, 4) marked and a dashed line from the origin. A struct box next to it shows real = 3.0, imag = 4.0.

The struct and its fields

Two floats, one for each part:

struct complex {
    float real;
    float imag;
};
                                

Same as every other struct — don't forget the semicolon. The order matters for the initializer list (real first, then imaginary), but not for anything else.

Member Type Meaning Example
realfloatThe real part (a in a + bi)c.real = 3.0f;
imagfloatThe imaginary part (b in a + bi)c.imag = 4.0f;

The two fields are floats because complex arithmetic often produces fractional results, even when the inputs are integers. The magnitude of 3 + 4i is 5 (a clean integer), but the magnitude of 1 + 1i is √2 ≈ 1.414 (not an integer). So starting with floats from the beginning saves you from a lot of narrowing conversions later.

Complete C Program

Program: define a complex number and print it

#include <stdio.h>
#include <math.h>

struct complex {
    float real;
    float imag;
};

void print_complex(struct complex c) {
    if (c.imag < 0)
        printf("%.2f - %.2fi\n", c.real, fabsf(c.imag));
    else
        printf("%.2f + %.2fi\n", c.real, c.imag);
}

int main(void) {
    struct complex c = {3.0f, 4.0f};
    print_complex(c);
    return 0;
}
                                    

And here's a version that reads the two parts from the user, so you can try any complex number:

Variant: read the complex number from the user

#include <stdio.h>
#include <math.h>

struct complex {
    float real;
    float imag;
};

int main(void) {
    struct complex c;

    printf("Enter real part: ");
    scanf("%f", &c.real);
    printf("Enter imaginary part: ");
    scanf("%f", &c.imag);

    if (c.imag < 0)
        printf("Complex : %.2f - %.2fi\n", c.real, fabsf(c.imag));
    else
        printf("Complex : %.2f + %.2fi\n", c.real, c.imag);
    return 0;
}
                                    

Both versions do the same printing. The first wraps it in a function so you can reuse it; the second inline it for a quick demonstration. The fabsf from <math.h> gives the absolute value of a float — that's what lets us print "3.00 - 4.00i" instead of the awkward "3.00 + -4.00i". You may need to link with -lm on Linux for fabsf, but most compilers resolve it automatically.

Program Output

3.00 + 4.00i
                                

And for the user-input version, try a complex number with a negative imaginary part:

Enter real part: 2.5
Enter imaginary part: -1.75
Complex : 2.50 - 1.75i
                                

Notice that -1.75 prints as "− 1.75i" — the minus sign is the separator, not part of the number. If you'd printed printf("%.2f + %.2fi", c.real, c.imag) without the if-else, you'd get "2.50 + -1.75i", which is ugly. The if-else and the fabsf fix that.

Step-by-Step Explanation

Short program, quick walk-through.

1. The struct

struct complex { float real; float imag; }; — two floats, one for each part. That's the whole data model for a complex number. The names are for humans; the compiler just remembers "two floats".

2. Declaring and filling

struct complex c = {3.0f, 4.0f}; creates a complex number 3 + 4i. The 3.0f goes into real, the 4.0f into imag. Or you can set them after declaring: c.real = 3.0f; c.imag = 4.0f;. Same thing, different lines.

3. The printing function

print_complex takes a struct complex by value (a small copy, fine for two floats) and prints it in two formats depending on the sign of imag. If imag is negative, it prints "%.2f - %.2fi" with fabsf(c.imag), which strips the sign. If imag is zero or positive, it prints "%.2f + %.2fi". This is the only subtle bit of the program.

4. Why the sign logic matters

In math, complex numbers are written as a + bi, but if b is negative, that formula becomes a + (−b)i, which looks wrong. People usually write it as a − |b|i, with the minus sign between the real and imaginary parts. So the formatting has to adapt to the sign of the imaginary part. It's a small point, but it's the difference between "3.00 + -4.00i" and "3.00 - 4.00i", which is the difference between a program that works and one that looks right.

5. The fabsf function

fabsf is the absolute value for floats. fabsf(-4.0f) returns 4.0f. It's in <math.h> — the same header that has sqrt. If you wanted a double version, use fabs; for long double, fabsl. The f in fabsf is for float.

6. The link flag on Linux

Just like with sqrt, using fabsf may require adding -lm when you compile on Linux: gcc complex.c -o complex -lm. Without it, the linker complains that fabsf is undefined. On macOS and Windows, it's usually automatic. It's the same gotcha we saw in the distance-between-points assignment.

7. Where this leads

Once you have the struct, arithmetic is straightforward. Adding two complex numbers means adding the real parts and the imaginary parts separately. Multiplying is a bit more involved — (a + bi) × (c + di) = (ac − bd) + (ad + bc)i — but it's still just arithmetic on the two fields. The magnitude is sqrt(real² + imag²). All of it uses the same struct. The next assignment (initializing and displaying) is basically what we did here, so this one is the foundation.

🎯 Remember this: a complex number is two floats — real and imag. Fill with {3.0f, 4.0f}. When printing, check the sign of imag and use + or - accordingly, with fabsf to strip the sign. Both fields are floats because complex arithmetic often produces fractions.

Frequently Asked Questions

1. Why use floats and not ints?

Because complex arithmetic almost always involves fractions. The square root of −1 isn't an integer; the magnitude of 1 + 1i is √2; dividing two complex numbers often produces fractional results. Floats handle all these cases naturally. Ints would truncate every calculation and give wrong answers. Use floats (or doubles) from the start — it's simpler than mixing types later.

2. Why check the sign of imag when printing?

Because the standard notation is a + bi when b is positive, and a − |b|i when b is negative. If you just do printf("%.2f + %.2fi", real, imag) without the check, a negative imaginary part prints as "2.50 + -1.75i" — which is technically correct but looks like a bug. The if-else and the fabsf give the clean "2.50 - 1.75i" that matches how math books write it.

3. What if the imaginary part is exactly zero?

With the current code, c.imag == 0 is not negative, so it goes to the else branch and prints "3.00 + 0.00i". Technically correct, but a bit redundant — many people would prefer to print just "3.00" when the imaginary part is zero, since that's a real number. You can add a check: if (c.imag == 0) printf("%.2f\n", c.real);. Whether you want that is a matter of style; the assignment doesn't require it.

4. Do I need math.h for fabsf?

Yes — fabsf is declared in <math.h>. Without it, the compiler assumes an implicit declaration and may give you a warning or a link error. Include #include <math.h> at the top, and on Linux add -lm when compiling. On macOS and Windows, the math library is usually linked automatically.

5. Can I use double instead of float?

Yes. double has about twice the precision (15 significant digits vs 7), which matters if you're doing many operations in a row and want to keep the errors small. The struct fields would be double instead of float, and you'd use fabs instead of fabsf. For teaching, float is fine. For numerical work, double is standard.

6. Could I use the standard library's complex.h instead?

Yes — C99 added <complex.h> with a built-in complex type and functions for all the standard operations. You can write double complex z = 3.0 + 4.0 * I; and print it with printf("%.2f + %.2fi", creal(z), cimag(z)). It's more powerful than rolling your own, but for learning how structs work, our version is clearer and shows exactly what's happening. In a real project, use complex.h.

💡 Tip: After this, try adding two complex numbers together. It's just two adds: result.real = a.real + b.real; and result.imag = a.imag + b.imag;. Then try the magnitude: sqrt(a.real * a.real + a.imag * a.imag). Both are small exercises that build on the same struct — the sort of thing that would be much messier without it.

📖 Related Tutorials

  • 23. Initialize and Display the Complex Number Using a Structure
  • 21. Give a Salary Hike to an Employee Using a Structure
  • 9. Find the Distance Between Two Points Using a Structure
  • Structures and Functions
  • Accessing Structure Members
  • Defining a Structure
  • Array of Structures
  • All 25 Structure Assignments

Previous Topic: -->> 21. Give a Salary Hike to an Employee Using a Structure   ||   Next Topic: -->> 23. Initialize and Display the Complex Number Using a Structure


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.