Let us use structure complex to represent a complex number and write a simple program containing only the main function. Thus, we can define structure complex either in the main function or before it as a global definition.
The addition of two complex numbers involves the addition of the real and imaginary parts of the two numbers. Let us use structure variables x and y to represent the complex numbers being added and the structure variable z to represent the result.
In the main function, we declare structure complex and variables x,y and z. Then we read two complex numbers from the keyboard, add them and print the result. The program is given below.
/* Addition of complex numbers: uses local structure definition */
#include <stdio.h>
int main ()
{
struct complex {
float re, im;
} x, y, z;
clrscr();
/* read complex numbers */
printf(“Enter real and imaginary parts of\n”);
printf(” complex number x: “);
scanf(“%f %f”, &x.re, &x.im);
printf(” complex number y: “);
scanf(“%f %f”, &y.re, &y.im);
/* add complex numbers */
z.re = x.re + y.re;
z.im = x.im + y.im;
/* print addition */
printf(“z.re = %4.2f z.im = %4.2f\n”, z.re, z.im);
return 0;
}