C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Structures in C

Complex number addition using structures

C Program: Addition of Two Complex Numbers using Structures

C

#include <stdio.h>

 

// Define structure for Complex Number

struct Complex {

    float real;

    float imag;

};

 

// Function declaration

struct Complex addComplex(struct Complex c1, struct Complex c2);

void displayComplex(struct Complex c);

 

int main() {

    struct Complex num1, num2, result;

 

    // Input first complex number

    printf("Enter first complex number (real and imaginary part): ");

    scanf("%f %f", &num1.real, &num1.imag);

 

    // Input second complex number

    printf("Enter second complex number (real and imaginary part): ");

    scanf("%f %f", &num2.real, &num2.imag);

 

    // Function call to add complex numbers

    result = addComplex(num1, num2);

 

    // Display result

    printf("\n--- Complex Number Addition ---\n");

    printf("First Number  = ");

    displayComplex(num1);

    printf("Second Number = ");

    displayComplex(num2);

    printf("Sum           = ");

    displayComplex(result);

 

    return 0;

}

 

// Function to add two complex numbers

struct Complex addComplex(struct Complex c1, struct Complex c2) {

    struct Complex temp;

    temp.real = c1.real + c2.real;

    temp.imag = c1.imag + c2.imag;

    return temp;

}

 

// Function to display complex number

void displayComplex(struct Complex c) {

    if (c.imag >= 0)

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

    else

        printf("%.2f - %.2fi\n", c.real, -c.imag);

}

Output

 
OUTPUT :
Enter first complex number (real and imaginary part): 3.5 2.5
Enter second complex number (real and imaginary part): 1.5 4.0

--- Complex Number Addition ---
First Number  = 3.50 + 2.50i
Second Number = 1.50 + 4.00i
Sum           = 5.00 + 6.50i

Explanation

Concept

Description

struct Complex

Defines a structure with real and imaginary parts.

addComplex()

Function that takes two structures and returns their sum as a structure.

displayComplex()

Displays the complex number in readable form (a + bi).

result = addComplex(num1, num2);

Stores the returned structure (sum) in result.