C Program to Add Two Complex Numbers
Last Updated :
30 May, 2023
Complex numbers are those numbers that can be expressed in the form of “a+ib” where a and b are the real numbers and i is the imaginary part called “iota” The value of i is √-1. In this article, we are going to add two complex numbers using a C program.
Example of Add Two Complex Number
Input:
a = ( 2 + 3i )
b = ( 4 + 5i )
Output:
Sum = ( 6 + 8i )
Explanation:
= ( 2 + 3i ) + ( 4 + 5i )
= ( 2 + 4 ) + ( 3 + 5 )i
= ( 6 + 8i )
Approach
The approach is very simple for this program, follow the below steps.
- Define a structure for complex numbers.
- Define a function for adding two complex numbers.
- This function accepts two complex numbers as parameters and returns a complex number.
Below is the C program to add two complex numbers:
C
#include <stdio.h>
typedef struct complexNumber {
int real;
int img;
} complex;
complex add(complex x, complex y);
int main()
{
complex a, b, sum;
a.real = 2;
a.img = 3;
b.real = 4;
b.img = 5;
printf ( "\n a = %d + %di" , a.real, a.img);
printf ( "\n b = %d + %di" , b.real, b.img);
sum = add(a, b);
printf ( "\n sum = %d + %di" , sum.real, sum.img);
return 0;
}
complex add(complex x, complex y)
{
complex add;
add.real = x.real + y.real;
add.img = x.img + y.img;
return (add);
}
|
Output
a = 2 + 3i
b = 4 + 5i
sum = 6 + 8i
Explanation of the above method
Complex Numbers consist of real and img parts which will be declared as a struct complex. While In the function, int main() there are three instances of structs created a,b, and sum. And then values are assigned to both complex numbers. After assigning the values we are calling add function with a and b as a complex number. add function will return the addition of both objects as a sum.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...