Exercise:
Write a C Program to add two complex numbers by passing structure to a function.
Click Here to View the Solution!
#include <stdio.h>
typedef struct complex {
float real;
float imag;
} complex;
complex add(complex n1, complex n2);
int main() {
complex n1, n2, result;
printf("For 1st complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n2.real, &n2.imag);
result = add(n1, n2);
printf("Sum = %.1f + %.1fi", result.real, result.imag);
return 0;
}
complex add(complex n1, complex n2) {
complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return (temp);
}
Click Here to View the Output!
For 1st complex number
Enter the real and imaginary parts: 3 2
For 2nd complex number
Enter the real and imaginary parts: 4 6
Sum = 7.0 + 8.0i
Click Here to View the Explanation!
- This program is used to calculate the sum of two complex numbers by passing the structure to a function.
- A
Structure complex
is created with twofloat type
membersreal
andimg
. - The program then creates two structure variables
n1
andn2
and passes them to afunction add()
. - The
function add()
is used to calculate the sum of two complex numbers and it returns the result as this structure which contains the sum. - In
main()
, the program requests the user to enter the first complex number by asking for both its real and imaginary parts and stores them in thestruct
variablesreal
andimg
using then1
. Similarly, the program requests and stores the second complex number. - The add function is then called in main whose output is stored in the variable
result
and is printed. - Finally, the
struct
complex typefunction add()
is initialized using the complex type temp variable. Both the real and imaginary values are added and stored in thevariable temp
which is returned to main for printing the sum of the complex numbers.