Write a C program that uses functions to perform the following Operations Reading a complex number, Writing a complex number, Addition of two complex numbers, Multiplication of two complex numbers
#include <stdio.h>
// Define a structure to represent a complex number
typedef struct {
float real;
float imag;
} Complex;
// Function to read a complex number
Complex readComplex() {
Complex c;
printf("Enter real part: ");
scanf("%f", &c.real);
printf("Enter imaginary part: ");
scanf("%f", &c.imag);
return c;
}
// Function to write (print) a complex number
void writeComplex(Complex c) {
if (c.imag >= 0)
printf("%.2f + %.2fi\n", c.real, c.imag);
else
printf("%.2f - %.2fi\n", c.real, -c.imag);
}
// Function to add two complex numbers
Complex addComplex(Complex c1, Complex c2) {
Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}
// Function to multiply two complex numbers
Complex multiplyComplex(Complex c1, Complex c2) {
Complex result;
result.real = c1.real * c2.real - c1.imag * c2.imag;
result.imag = c1.real * c2.imag + c1.imag * c2.real;
return result;
}
int main() {
Complex c1, c2, sum, product;
printf("Enter the first complex number:\n");
c1 = readComplex();
printf("Enter the second complex number:\n");
c2 = readComplex();
// Display the complex numbers
printf("First complex number: ");
writeComplex(c1);
printf("Second complex number: ");
writeComplex(c2);
// Perform addition
sum = addComplex(c1, c2);
printf("Sum of the complex numbers: ");
writeComplex(sum);
// Perform multiplication
product = multiplyComplex(c1, c2);
printf("Product of the complex numbers: ");
writeComplex(product);
return 0;
}
Comments
Post a Comment