C Program to Add Two Complex Numbers by Passing Structure to a Function
ADVERTISEMENTS
C Program to Add Two Complex Numbers by Passing Structure to a Function.
In this article, you will learn how to add two complex numbers by passing the structure to a function.
Example
Enter the real & imaginary numbers of 1st Complex:
1.5
3.6
Enter the real & imaginary numbers of 2nd Complex:
-3.4
6.8
Sum = -1.9 + 10.4i
You should know about the following topics in C programming to understand this program:
- C Structure
- C Functions
Source
// C Program to Add Two Complex Numbers by Passing Structure to a Function
#include <stdio.h>
// Make structure of the complex number
typedef struct complex_number {
float real_num;
float imaginary_num;
} complex_number;
// Custom function to sum the complex numbers
complex_number sum_complex(complex_number num1, complex_number num2) {
complex_number temp_num;
temp_num.real_num = num1.real_num + num2.real_num;
temp_num.imaginary_num = num1.imaginary_num + num2.imaginary_num;
return (temp_num);
}
// It's the main function of the program
int main() {
// declare the variables here
complex_number num1, num2, result;
// Step-1 INPUT of the 1st Complex
printf("Enter the real & imaginary numbers of 1st Complex:\n");
scanf("%f %f", &num1.real_num, &num1.imaginary_num);
// Step-2 INPUT of the 2nd Complex
printf("\nEnter the real & imaginary numbers of 2nd Complex:\n");
scanf("%f %f", &num2.real_num, &num2.imaginary_num);
// Step-3 Call the function to add the Complex
result = sum_complex(num1, num2);
// Step-4 Final output of the program
printf("\nSum = %.1f + %.1fi\n", result.real_num, result.imaginary_num);
return 0;
}
Output
Enter the real & imaginary numbers of 1st Complex:
4.3
-5.1
Enter the real & imaginary numbers of 2nd Complex:
9.0
11.7
Sum = 13.3 + 6.6i