- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to Add Two Complex Numbers in C
Given are the two complex numbers in the form of a1+ ib1 and a2 + ib2, the task is to add these two complex numbers.
Complex numbers are those numbers which can be expressed in the form of “a+ib” where “a” and “b” are the real numbers and i is the imaginary number which is the solution of the expression 𝑥 2 = −1 as no real number satisfies the equation that’s why it is called as imaginary number.
Input
a1 = 3, b1 = 8 a2 = 5, b2 = 2
Output
Complex number 1: 3 + i8 Complex number 2: 5 + i2 Sum of the complex numbers: 8 + i10
Explanation
(3+i8) + (5+i2) = (3+5) + i(8+2) = 8 + i10
Input
a1 = 5, b1 = 3 a2 = 2, b2 = 2
Output
Complex number 1: 5 + i3 Complex number 2: 2 + i2 Sum of the complex numbers: 7 + i5
Explanation
(5+i3) + (2+i2) = (5+2) + i(3+2) = 7 + i5
Approach used below is as follows to solve the problem
Declare a struct for storing the real and imaginary numbers.
Take the input and add the real numbers and imaginary numbers of all the complex numbers.
Algorithm
Start Decalre a struct complexnum with following elements 1. real 2. img In function complexnum sumcomplex(complexnum a, complexnum b) Step 1→ Declare a signature struct complexnum c Step 2→ Set c.real as a.real + b.real Step 3→ Set c.img as a.img + b.img Step 4→ Return c In function int main() Step 1→ Declare and initialize complexnum a = {1, 2} and b = {4, 5} Step 2→ Declare and set complexnum c as sumcomplex(a, b) Step 3→ Print the first complex number Step 4→ Print the second complex number Step 5→ Print the sum of both in c.real, c.img Stop
Example
#include <stdio.h> //structure for storing the real and imaginery //values of complex number struct complexnum{ int real, img; }; complexnum sumcomplex(complexnum a, complexnum b){ struct complexnum c; //Adding up two complex numbers c.real = a.real + b.real; c.img = a.img + b.img; return c; } int main(){ struct complexnum a = {1, 2}; struct complexnum b = {4, 5}; struct complexnum c = sumcomplex(a, b); printf("Complex number 1: %d + i%d
", a.real, a.img); printf("Complex number 2: %d + i%d
", b.real, b.img); printf("Sum of the complex numbers: %d + i%d
", c.real, c.img); return 0; }
Output
If run the above code it will generate the following output −
Complex number 1: 1 + i2 Complex number 2: 4 + i5 Sum of the complex numbers: 5 + i7
Advertisements