A complex number is a number that can be expressed in the form a + bi, where a and b are real numbers and i is the imaginary unit, which satisfies the equation i2 = -1. In complex number a + bi, a is the real part and b is the imaginary part. For example: (2 + 3i) is a complex number.
Complex Number Arithmetic
Addition of Complex Numbers
Consider two complex numbers C1 = (a + ib) and C2 = (c + id) Let Sum(x + iy) is the sum of C1 and C2 Sum = C1 + C2 (x + iy) = (a + ib) + (c + id) (x + iy) = (a + c) + i(b + d) x = (a + c) and, y = (b + d)
Subtraction of Complex Numbers
Let Diff(x + iy) is the difference of C1 and C2 Diff = C1 - C2 (x + iy) = (a + ib) - (c + id) (x + iy) = (a - c) + i(b - d) x = (a - c) and, y = (b - d)
C program to add two complex numbers using structures
Here we are using a user defined structure 'complexNumber' that contains two integer data members to store real and imaginary part of complex number. A structure provides an encapsulation to represent a complex number as an single entity instead of using two variables to store a complex number.
In this program we take two complex numbers as input from user in the form of A + iB. We will add real parts of input complex number to get the real part of sum complex and add imaginary part of input complex to get imaginary part of sum complex number. Then we print sum complex number.
#include <stdio.h> typedef struct complex { int real; int imaginary; } complexNumber; int main() { complexNumber firstCN, secondCN, sumCN; printf("Enter value of A and B for (A + iB)\n"); scanf("%d %d", &firstCN.real, &firstCN.imaginary); printf("Enter value of C and D for (C + iD)\n"); scanf("%d %d", &secondCN.real, &secondCN.imaginary); /*(A + Bi)+(C + Di) = (A+C) + (B+D)i */ sumCN.real = firstCN.real + secondCN.real; sumCN.imaginary = firstCN.imaginary + secondCN.imaginary; if (sumCN.imaginary >= 0 ) printf("SUM = %d + %di\n", sumCN.real, sumCN.imaginary); else printf("SUM = %d %di\n", sumCN.real, sumCN.imaginary); return 0; }Output
Enter value of A and B for (A + iB) 2 3 Enter value of C and D for (C + iD) 3 4 SUM = 5 + 7i
C program to subtract two complex numbers using structures
#include <stdio.h> typedef struct complex { int real; int imaginary; } complexNumber; int main() { complexNumber firstCN, secondCN, sumCN; printf("Enter value of A and B for (A + iB)\n"); scanf("%d %d", &firstCN.real, &firstCN.imaginary); printf("Enter value of C and D for (C + iD)\n"); scanf("%d %d", &secondCN.real, &secondCN.imaginary); /* (A + Bi) - (C + Di) = (A-C) + (B-D)i */ sumCN.real = firstCN.real - secondCN.real; sumCN.imaginary = firstCN.imaginary - secondCN.imaginary; if (sumCN.imaginary >= 0 ) printf("DIFFERENCE = %d + %di\n", sumCN.real, sumCN.imaginary); else printf("DIFFERENCE = %d %di\n", sumCN.real, sumCN.imaginary); return 0; }Output
Enter value of A and B for (A + iB) 5 4 Enter value of C and D for (C + iD) 2 2 DIFFERENCE = 3 + 2iRelated Topics