C Program for Complex Number Operations
Subject: DataStructures Through C
Contributed By: Sanjay
Created At: February 3, 2025
Question:
Write a C Program for Complex Number Operations (Addition, Subtraction, Multiplication)
Explanation Video:
Explanation:
Complex Operations:
- A complex number has a real and imaginary part.
- The program adds, subtracts, and multiplies two complex numbers.
Source Code:
#include <stdio.h>
struct Complex {
float real;
float imag;
};
struct Complex add(struct Complex a, struct Complex b) {
struct Complex result;
result.real = a.real + b.real;
result.imag = a.imag + b.imag;
return result;
}
struct Complex subtract(struct Complex a, struct Complex b) {
struct Complex result;
result.real = a.real - b.real;
result.imag = a.imag - b.imag;
return result;
}
struct Complex multiply(struct Complex a, struct Complex b) {
struct Complex result;
result.real = a.real * b.real - a.imag * b.imag;
result.imag = a.real * b.imag + a.imag * b.real;
return result;
}
int main() {
struct Complex c1, c2, sum, diff, product;
printf("Enter real and imaginary parts of first complex number: ");
scanf("%f %f", &c1.real, &c1.imag);
printf("Enter real and imaginary parts of second complex number: ");
scanf("%f %f", &c2.real, &c2.imag);
sum = add(c1, c2);
diff = subtract(c1, c2);
product = multiply(c1, c2);
printf("\nSum: %.2f + %.2fi", sum.real, sum.imag);
printf("\nDifference: %.2f + %.2fi", diff.real, diff.imag);
printf("\nProduct: %.2f + %.2fi\n", product.real, product.imag);
return 0;
}
Input:
Enter real and imaginary parts of first complex number: 3 2
Enter real and imaginary parts of second complex number: 1 4
Output:
Sum: 4.00 + 6.00i
Difference: 2.00 - 2.00i
Product: -5.00 + 14.00i