# 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.

## C Source Code: Complex Multiplication

``````
#include<stdio.h>

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

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

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 *p, struct complex *q)
{
struct 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 `struct 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:

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

----------------
WITH NO POINTER
----------------
cnum1.real & cnum1.imaginary gives member value.
cnum2.real & cnum2.imaginary gives member value.
----------------
WITH POINTER
----------------
From the concept of pointer
referencing & dereferencing
member 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
```