Add Complex Numbers by Passing Structure to a Function in C

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 two float type members real and img.
  • The program then creates two structure variables n1 and n2 and passes them to a function 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 the struct variables real and img using the n1. 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 type function add() is initialized using the complex type temp variable. Both the real and imaginary values are added and stored in the variable temp which is returned to main for printing the sum of the complex numbers.

%d bloggers like this: