C Program to Add Two Complex Numbers by Passing Structure to a Function

This program takes two complex numbers as structures and adds them with the use of functions.

Example: Add Two Complex Numbers

  1. #include <stdio.h>
  2. typedef struct complex
  3. {
  4. float real;
  5. float imag;
  6. } complex;
  7. complex add(complex n1,complex n2);
  8. int main()
  9. {
  10. complex n1, n2, temp;
  11. printf("For 1st complex number \n");
  12. printf("Enter real and imaginary part respectively:\n");
  13. scanf("%f %f", &n1.real, &n1.imag);
  14. printf("\nFor 2nd complex number \n");
  15. printf("Enter real and imaginary part respectively:\n");
  16. scanf("%f %f", &n2.real, &n2.imag);
  17. temp = add(n1, n2);
  18. printf("Sum = %.1f + %.1fi", temp.real, temp.imag);
  19. return 0;
  20. }
  21. complex add(complex n1, complex n2)
  22. {
  23. complex temp;
  24. temp.real = n1.real + n2.real;
  25. temp.imag = n1.imag + n2.imag;
  26. return(temp);
  27. }

Output

For 1st complex number
Enter real and imaginary part respectively: 2.3
4.5

For 2nd complex number
Enter real and imaginary part respectively: 3.4
5
Sum = 5.7 + 9.5i

In this program, structures n1 and n2 are passed as an argument of function add().

This function computes the sum and returns the structure variable temp to the main() function.