Structure Assignment 23 — Initialize and Display a Complex Number Using a Structure
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Initialize and Display a Complex Number Using a Structure

📑 On this page:
  • What a complex number is
  • Designing the struct
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to model a complex number with a struct that has two members
  • Two ways to initialize a struct — at declaration and after
  • How to access and print struct members with the dot operator
  • How to format the output as a + bi using printf
  • Why a struct is the right choice here instead of two separate variables

What a complex number is

A complex number has two parts: a real part and an imaginary part. It's written as a + bi, where a is the real part, b is the imaginary part, and i is the square root of −1. For example, 3 + 4i has a real part of 3 and an imaginary part of 4.

In C, there's no built-in complex type. You could store the two parts in two separate variables — float real = 3.0; and float imag = 4.0; — but then every time you pass the number to a function, you have to pass both. And if you have an array of complex numbers, you'd need two parallel arrays. That gets messy fast.

A struct solves this by bundling the two parts into one unit. You can pass a whole complex number to a function with one parameter, store an array of complex numbers in a single array, and keep the two parts together wherever the number goes. That's exactly what a struct is for.

💡 In one line: a complex number is two floats — real and imaginary — and a struct keeps them together as one value. Define the struct, initialize a variable, print the two parts with the + and i in the right places.

A complex number 3 + 4i shown with its real part 3 on the horizontal axis and imaginary part 4 on the vertical axis, illustrating how a struct stores both parts together.

Designing the struct

The struct has exactly two members, both floats:

struct complex {
    float real;
    float imag;
};
                                

That's it. Two members, named to match the math. real holds the real part, imag holds the imaginary part. Using float means you can represent numbers like 3.5 + 2.25i — not just integers. If you wanted more precision, you'd use double. For this assignment, float is enough.

Once the struct is defined, you can declare variables of that type. The syntax is struct complex c; — same as any other struct. And you can initialize it right at declaration:

struct complex c = {3.0, 4.0};
                                

The values go in order: first real, then imag. So this sets c.real = 3.0 and c.imag = 4.0. That's the shortest way to initialize a struct.

Member Type Holds Example
realfloatReal part3.0
imagfloatImaginary part4.0

Complete C Program

Program: initialize at declaration and display

#include <stdio.h>

struct complex {
    float real;
    float imag;
};

int main(void) {
    struct complex c = {3.0, 4.0};

    printf("Complex number: %.2f + %.2fi\n", c.real, c.imag);

    return 0;
}
                                    

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

Variant: read from the user

#include <stdio.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);

    printf("\nComplex number: %.2f + %.2fi\n", c.real, c.imag);

    return 0;
}
                                    

And here's a third version that uses a separate function to display the number — useful once the main program grows and you want to keep the printing logic in one place:

Variant: with a display function

#include <stdio.h>

struct complex {
    float real;
    float imag;
};

void display(struct complex c) {
    printf("%.2f + %.2fi\n", c.real, c.imag);
}

int main(void) {
    struct complex c = {3.0, 4.0};

    printf("Complex number: ");
    display(c);

    return 0;
}
                                    

All three versions use the same struct. The differences are just where the data comes from (hard-coded, user input) and where the printing happens (in main, in a helper function). The core idea — two members, dot access, formatted print — is the same in every version.

Program Output

For the first version (hard-coded {3.0, 4.0}):

Complex number: 3.00 + 4.00i
                                

For the user-input version, try different values:

Enter real part: 5.5
Enter imaginary part: -2.25

Complex number: 5.50 + -2.25i
                                

Notice the awkward + -2.25i in that output. It's technically correct — the value of imag is negative — but it reads poorly. A better program would check the sign and print either + 2.25i or - 2.25i depending on whether the imaginary part is positive or negative. We'll show how to fix that in the explanation.

For the version with a display function, the output is the same:

Complex number: 3.00 + 4.00i
                                

Step-by-Step Explanation

Let's walk through the key pieces.

1. The struct definition

struct complex { float real; float imag; }; creates a new type. It's not a variable yet — it's a template. Two members, both floats. The semicolon at the end is required; forgetting it is a common beginner mistake.

2. Declaring a variable

struct complex c; creates one variable named c of type struct complex. At this point the two members hold garbage values — they haven't been set yet. That's why you should always initialize a struct before reading from it.

3. Initializing at declaration

struct complex c = {3.0, 4.0}; sets c.real to 3.0 and c.imag to 4.0. The order matters — the first value goes to the first member, the second to the second. If you wrote {4.0, 3.0}, you'd get real = 4.0 and imag = 3.0, which is a different complex number.

4. Accessing members

The dot operator gets you inside the struct. c.real reads the real part, c.imag reads the imaginary part. You can also assign to them: c.real = 5.0; changes the real part. The dot works for reading and writing, both.

5. Printing the number

printf("%.2f + %.2fi\n", c.real, c.imag) prints the real part with two decimal places, then the literal string + , then the imaginary part with two decimal places, then the literal i, then a newline. The %.2f format specifier means "print a float with two digits after the decimal point." Change the 2 to change the precision.

6. Handling negative imaginary parts properly

The basic printf gives you + -2.25i when the imaginary part is negative. A cleaner version checks the sign first:

if (c.imag >= 0)
    printf("%.2f + %.2fi\n", c.real, c.imag);
else
    printf("%.2f - %.2fi\n", c.real, -c.imag);
                                

When the imaginary part is negative, print - and the absolute value. When it's zero or positive, print + and the value as-is. That's the standard way complex numbers are written.

7. Why a struct instead of two variables?

Two separate floats work for one complex number. But as soon as you have two complex numbers, or an array of them, or functions that operate on them, the struct pays off. You can pass one value instead of two. You can return one value instead of two. You can write struct complex add(struct complex a, struct complex b) and the function signature says exactly what it does. That's the design principle at work: keep related data together.

🎯 Remember this: a struct bundles two related values into one type. Define it once, use it as many times as you need. Initialize at declaration with {real, imag}, access members with the dot operator, and print with a format string that inserts the + and i where they belong.

Frequently Asked Questions

1. Why use float instead of int for the members?

Because complex numbers often have fractional parts — 3.5 + 2.25i, for example. If you use int, you can only store whole numbers. Using float lets you store decimals, and it's the standard choice for this kind of numeric struct. If you need more precision, use double; if you need less memory, use float. For this assignment, float is the right middle ground.

2. What does %.2f mean in the printf?

It means "print a float with exactly two digits after the decimal point." So 3.0 prints as 3.00, and 4.567 prints as 4.57 (rounded). If you used %f without the .2, printf would print six digits after the decimal by default — 3.000000. The .2 keeps the output short and readable.

3. Why does my output show + -2.25i when the imaginary part is negative?

Because printf prints the + as a literal character, and then prints the value of imag — which happens to be negative. So you get + then -2.25, which reads as + -2.25i. The fix is to check the sign in code and choose whether to print + or - accordingly. See the "Handling negative imaginary parts" section above for the exact code.

4. Can I initialize the struct after declaring it?

Yes. You can declare it first and assign members one by one: struct complex c; c.real = 3.0; c.imag = 4.0;. This is useful when the values come from user input or from a calculation — you don't have them at declaration time. The initializer-list form {3.0, 4.0} is shorter when you do have the values ready.

5. What if the imaginary part is zero?

Then the number is purely real. With the sign-check code above, c.imag >= 0 is true, so it prints + 0.00i. That's technically correct but slightly ugly. A nicer version would check if (c.imag == 0) and skip the imaginary part entirely. For this assignment, printing + 0.00i is fine.

6. Can I add two complex numbers using this struct?

Yes — that's the natural next step. Write a function struct complex add(struct complex a, struct complex b) that creates a new struct, sets result.real = a.real + b.real and result.imag = a.imag + b.imag, and returns it. The same pattern works for subtraction, multiplication (using the FOIL rule), and division (multiplying by the conjugate). The struct makes all of these clean, because you're always passing one value instead of two.

💡 Tip: After this, try adding a function that adds two complex numbers and prints the result. Then try multiplying them — the formula is (a.real*b.real - a.imag*b.imag) + (a.real*b.imag + a.imag*b.real)i. Try storing an array of five complex numbers and printing all of them. Try reading from the user and handling negative imaginary parts correctly. Each of these builds on the same struct and the same dot-access pattern.

📖 Related Tutorials

  • Introduction to Structures
  • Defining a Structure
  • Declaring Structure Variables
  • Accessing Structure Members
  • Structure Initialization
  • Create a Structure to Represent a Date
  • Initialize and Display the Date Using a Structure
  • All 25 Structure Assignments

Previous Topic: -->> 14. Initialize and Display the Date Using a Structure   ||   All Assignments: -->> All 25 Structure Assignments   ||   Next Topic: -->> 16. Create a Structure to Represent a Time


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.