C Program to Multiply Two Complex Number Using User Defined Function

In this C programming example we present two different approach to multiply two complex number using user defined function. First, we use structure and user defined function. Second, we use structure, typedef and user defined function.

Using Structure & User Defined Function

Following C program multiplies two complex number using structure and user defined function.

C Source Code


#include<stdio.h>

/* Declaring Structure */
struct complex
{
    float real;
    float imaginary;
};

/* Function Prototype */
struct complex multiply(struct complex a, struct complex b);

/* Main Function */
int main()
{
    /* Declaring structure variable using struct complex */
    struct complex cnum1, cnum2, mul;
    printf("Enter real and imaginary part of first complex number:\n");
    scanf("%f%f", &cnum1.real, &cnum1.imaginary);
    printf("Enter real and imaginary part of second complex number:\n");
    scanf("%f%f", &cnum2.real, &cnum2.imaginary);

    mul = multiply(cnum1, cnum2);

    printf("PRODUCT = %0.2f + i %0.2f", mul.real, mul.imaginary);

    return 0;
}

/* Function Definition */
struct complex multiply(struct complex a, struct complex b)
{
    struct complex m;

    m.real = a.real * b.real - a.imaginary * b.imaginary;
    m.imaginary = a.real * b.imaginary + b.real * a.imaginary;

    return m;
}

Output

Enter real and imaginary part of first complex number:
1
5
Enter real and imaginary part of second complex number:
2
7
PRODUCT = -33.00 + i 17.00

Using Structure, Typedef & User Defined Function

Following C program multiplies two complex number using structure, typedef and user defined function.

C Source Code


#include<stdio.h>

/* Declaring Structure */
typedef struct
{
    float real;
    float imaginary;
}complex;

/* Function Prototype */
complex multiply(complex a, complex b);

/* Main Function */
int main()
{
    /* Declaring structure variable using struct complex */
    complex cnum1, cnum2, mul;
    printf("Enter real and imaginary part of first complex number:\n");
    scanf("%f%f", &cnum1.real, &cnum1.imaginary);
    printf("Enter real and imaginary part of second complex number:\n");
    scanf("%f%f", &cnum2.real, &cnum2.imaginary);

    mul = multiply(cnum1, cnum2);

    printf("PRODUCT = %0.2f + i %0.2f", mul.real, mul.imaginary);

    return 0;
}

/* Function Definition */
complex multiply(complex a, complex b)
{
    complex m;

    m.real = a.real * b.real - a.imaginary * b.imaginary;
    m.imaginary = a.real * b.imaginary + b.real * a.imaginary;

    return m;
}

Output

Enter real and imaginary part of first complex number:
1
5
Enter real and imaginary part of second complex number:
2
7
PRODUCT = -33.00 + i 17.00