C Program to Multiply Two Complex Number Using Structure & Pointer

This C program multiplies two complex number given by user using the concept of structure and pointer.

Complex Number Multiplication Using Structure & Pointer


#include<stdio.h>

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

/* Function Prototype */
complex multiply(complex *p, complex *q);

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 *p, complex *q)
{
    complex temp;
    temp.real = p->real * q->real - p->imaginary * q->imaginary;
    temp.imaginary = p->real * q->imaginary + q->real * p->imaginary;
    return temp;
}

Code Explanation

Here complex is new data type which has been used to create structure variables cnum1, cnum2, mul & temp and pointers to structure i.e. p & q.

When using pointer with structure, structure elements are accessed using -> (called ARROW operator). To understand it more clearly, consider following code along with explanation:

complex cnum1, cnum2, *p, *q;
p = &cnum1; /* p is pointing cnum1 */
q = &cnum2; /* q is pointing cnum1 */

----------------
WITH NO POINTER 
----------------
cnum1.real & cnum1.imaginary gives memeber value.
cnum2.real & cnum2.imaginary gives memeber value.
----------------
WITH POINTER 
----------------
From the concept of pointer 
referencing & dereferencing 
memeber value looks like: 

*p.real & *p.imaginary gives member value
BUT IT IS NOT CORRECT

You need to use parentheses in 
name of pointer to structure
like this:
(*p).real and (*p).imaginary

WAIT , in C there is a better way!

(*p).real is equivalent to p->real, and
(*p).imaginary is equivalent to p->imaginary

SO
p->real, p->imaginary, q->real & q->imaginary
ARE CORRECT WAY OF ACCESSING MEMEBR VALUE
in this example.

Output

Enter real and imaginary part of first complex number:
1
2
Enter real and imaginary part of second complex number:
3
4
PRODUCT = -5.00 + i 10.00