Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Write a program to add two complex numbers using C
In C programming, complex numbers are mathematical entities that consist of real and imaginary parts. A complex number is represented in the form a + bi, where 'a' is the real part and 'b' is the imaginary part multiplied by 'i' (the square root of -1).
Syntax
struct complexNumber {
int real;
int imaginary;
};
Algorithm
To add two complex numbers, we add their real parts separately and imaginary parts separately −
- Real part: result_real = num1_real + num2_real
- Imaginary part: result_imaginary = num1_imaginary + num2_imaginary
Example
The following program demonstrates addition of two complex numbers using structures −
#include <stdio.h>
struct complexNumber {
int real, imaginary;
};
int main() {
struct complexNumber num1, num2, sum;
printf("Enter first complex number (real imaginary): ");
scanf("%d %d", &num1.real, &num1.imaginary);
printf("Enter second complex number (real imaginary): ");
scanf("%d %d", &num2.real, &num2.imaginary);
/* Add real and imaginary parts separately */
sum.real = num1.real + num2.real;
sum.imaginary = num1.imaginary + num2.imaginary;
printf("First complex number: %d + %di<br>", num1.real, num1.imaginary);
printf("Second complex number: %d + %di<br>", num2.real, num2.imaginary);
printf("Sum: %d + %di<br>", sum.real, sum.imaginary);
return 0;
}
Enter first complex number (real imaginary): 4 2 Enter second complex number (real imaginary): 5 3 First complex number: 4 + 2i Second complex number: 5 + 3i Sum: 9 + 5i
Key Points
- Complex numbers are represented using structures with real and imaginary components.
- Addition is performed by adding corresponding parts: real with real, imaginary with imaginary.
- The result follows the mathematical rule:
(a + bi) + (c + di) = (a + c) + (b + d)i
Conclusion
Adding complex numbers in C is straightforward using structures to represent the real and imaginary parts. This approach allows us to perform mathematical operations on complex numbers efficiently while maintaining code readability.
Advertisements
