C Program to Add 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 add or subtract two complex numbers, just add or subtract the corresponding real and imaginary parts. For instance, the sum of 6 + 3i and 4 + 2i is 10 + 5i.
In this tutorial, we are going to implement C program to add two complex number using structure. Structure is convenient for handling complex number since it has two parts real and imaginary parts.
C Program to Add 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, sum;
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);
sum.real = cnum1.real + cnum2.real;
sum.imaginary = cnum1.imaginary + cnum2.imaginary;
printf("SUM = %0.2f + i %0.2f", sum.real, sum.imaginary);
return 0;
}
Output of the Above Program
Enter real and imaginary part of first complex number: 2 3 Enter real and imaginary part of second complex number: 5 6 SUM = 7.00 + i 9.00
Modifying Above Program Using typedef
#include<stdio.h>
/* Declaring Structure */
typedef struct
{
float real;
float imaginary;
}complex;
int main()
{
/* Declaring structure variable using complex */
complex cnum1, cnum2, sum;
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);
sum.real = cnum1.real + cnum2.real;
sum.imaginary = cnum1.imaginary + cnum2.imaginary;
printf("SUM = %0.2f + i %0.2f", sum.real, sum.imaginary);
return 0;
}
Output
Enter real and imaginary part of first complex number: 7 3 Enter real and imaginary part of second complex number: 2 5 SUM = 9.00 + i 8.00