In this article, we will write a C program to add two complex numbers. A complex number is represented in the form of a + bi, where a is the real part, b is the imaginary part, and i is the imaginary unit (√(-1)).
Example:
Input: Z1 = 4 + 2i, Z2 = 2 + 7i Output: 6 + 9i Explanation: Z3 = Z1 + Z2 = (4 + 2i) + (2 + 7i) = (4 + 2) + (2 + 7)i = 6 + 9i
Steps to Add Two Complex Numbers.
Below are the steps that need to follow to add two complex numbers:
Step 1: Input the real and imaginary parts of the first complex number.
Step 2: Input the real and imaginary parts of the second complex number.
Step 3: Add the real parts of both complex numbers.
Step 4: Add the imaginary parts of both complex numbers.
Step 5: Display the sum of the complex numbers.
C program to add two complex numbers.
//C program to add two complex numbers #include <stdio.h> struct complex { float real; float imag; }; int main() { struct complex z1, z2, sum; printf("Enter first complex number (a + bi):\n"); scanf("%f %f", &z1.real, &z1.imag); printf("Enter second complex number (a + bi):\n"); scanf("%f %f", &z2.real, &z2.imag); // Add the real parts of both complex numbers sum.real = z1.real + z2.real; // Add the imaginary parts of both complex numbers sum.imag = z1.imag + z2.imag; printf("Sum of the complex numbers: %.2f + %.2fi\n", sum.real, sum.imag); return 0; }
Enter first complex number (a + bi):
2 3
Enter second complex number (a + bi):
4 5
Sum of the complex numbers: 6.00 + 8.00i
In the above example code, the struct part is used to define a user-defined data type called complex. This custom data type allows us to group two floating-point variables (real and imag) together, representing the real and imaginary parts of a complex number.
Then we created two complex type variables, z1, and z2, and one sum variable to store the result of addition.
No comments:
Post a Comment