Complex numbers are numbers that can be expressed in the form a + ib, where a and b are real numbers and i is the imaginary unit with a value of √-1.
- The real part is represented by a, while b represents the coefficient of the imaginary part.
- In this program, we add two complex numbers by separately adding their real and imaginary parts.
Illustration
Input:
a = 2 + 3i
b = 4 + 5iOutput:
Sum = 6 + 8i
Explanation:
(2 + 3i) + (4 + 5i)
= (2 + 4) + (3 + 5)i
= 6 + 8i
Approach
- Define a structure to store the real and imaginary parts of a complex number.
- Create a function that accepts two complex numbers and returns their sum.
- Add the real parts and imaginary parts separately.
- Print the resulting complex number.
Example: Program to Add Two Complex Numbers Using Structure and Function
#include <stdio.h>
typedef struct {
int real;
int img;
} Complex;
Complex add(Complex x, Complex y)
{
Complex sum;
sum.real = x.real + y.real;
sum.img = x.img + y.img;
return sum;
}
int main()
{
Complex a = {2, 3};
Complex b = {4, 5};
Complex sum = add(a, b);
printf("a = %d + %di\n", a.real, a.img);
printf("b = %d + %di\n", b.real, b.img);
printf("sum = %d + %di\n", sum.real, sum.img);
return 0;
}
Output
a = 2 + 3i b = 4 + 5i sum = 6 + 8i
Explanation: The Complex structure stores the real and imaginary parts of each number. The add() function adds the corresponding parts of the two complex numbers and returns the resulting Complex structure.