C Program to Multiply Two Complex Number Using Structure
We know that all complex numbers are of the form A + i B, where A is known as Real part of complex number and B is known as Imaginary part of complex number.
To multiply two complex numbers a + ib and c + id, we perform (ac - bd) + i (ad+bc). For example: multiplication of 1+2i and 2+1i will be 0+5i.
In this tutorial, we are going to implement C program to multiply two complex number using structure. Structure is convenient for handling complex number since it has two parts real and imaginary parts.
C Program to Multiply Two Complex Number
#include<stdio.h>
/* Declaring Structure */
struct complex
{
float real;
float imaginary;
};
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.real = cnum1.real * cnum2.real - cnum1.imaginary * cnum2.imaginary;
mul.imaginary = cnum1.real * cnum2.imaginary + cnum2.real * cnum1.imaginary;
printf("PRODUCT = %0.2f + i %0.2f", mul.real, mul.imaginary);
return 0;
}
Output of the Above Program
Enter real and imaginary part of first complex number: 3 4 Enter real and imaginary part of second complex number: 4 4 PRODUCT = -4.00 + i 28.00
Modifying Above Program Using typedef
#include<stdio.h>
/* Declaring Structure */
typedef struct
{
float real;
float imaginary;
};
int main()
{
/* Declaring structure variable using 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.real = cnum1.real * cnum2.real - cnum1.imaginary * cnum2.imaginary;
mul.imaginary = cnum1.real * cnum2.imaginary + cnum2.real * cnum1.imaginary;
printf("PRODUCT = %0.2f + i %0.2f", mul.real, mul.imaginary);
return 0;
}
Output
Enter real and imaginary part of first complex number: 1 2 Enter real and imaginary part of second complex number: 2 1 PRODUCT = 0.00 + i 5.00