Write a C Program to Add Two Complex Numbers.
In this article, we will add two complex numbers. We will take the real and imaginary parts of the two complex numbers as input from the user and then perform the addition operation. Complex numbers have the form 'a + bi', where 'a' is the real part and 'b' is the imaginary part.
Here's a C program to add two complex numbers:
#include<stdio.h>
#include<conio.h>
void main()
{
// Declare variables to store real and imaginary parts of two complex numbers
float real1, imag1, real2, imag2;
// Read the first complex number from the user
printf("Enter the real and imaginary parts of the first complex number (a + bi): ");
scanf("%f %f", &real1, &imag1);
// Read the second complex number from the user
printf("Enter the real and imaginary parts of the second complex number (a + bi): ");
scanf("%f %f", &real2, &imag2);
// Perform addition of the complex numbers
float sum_real = real1 + real2;
float sum_imag = imag1 + imag2;
// Display the result of addition
printf("Sum of the two complex numbers: %.2f + %.2fi\n", sum_real, sum_imag);
}
- The program begins by declaring the variables real1, imag1, real2, and imag2 to store the real and imaginary parts of the two complex numbers.
- The user is prompted to enter the real and imaginary parts of the first complex number, and the input is read using scanf.
- Similarly, the user is prompted to enter the real and imaginary parts of the second complex number, and this input is also read using scanf.
- Next, we perform the addition operation by adding the real parts and imaginary parts separately and store them in sum_real and sum_imag variables.
- Finally, we display the result of the addition of the two complex numbers using printf. The output is displayed in the form 'a + bi', where 'a' is the sum of real parts and 'b' is the sum of imaginary parts.
Output: