Related Tags

c
communitycreator

# How to add two complex numbers in C

Srivasthavi Mannepula

## Step 1

First, we need to understand what we need to do, which is add two complex numbers, like so:

• sum of real numbers + sum of imaginary numbers(i)

### Example

complex number 1:

$a+ib$

complex number 2:

$c+id$

sum :

$(a+b) + i(c+d)$

## Step 2

Next, we have to see what variables we need to declare:

#include<stdio.h>
struct Comp{
float r;
float i;
}c1,c2,res;


Here, we declare the structure and take two float variables (r for real numbers and i for complex numbers). Then, we will take the pointers (c1 and c2 for complex number one and complex number two and res for summation result).

## Step 3

Next, we take the input from the user:

int main(){
printf("enter the 1st complex
number:");
printf("\n real part= ");
scanf("%f",&c1.r);
printf("\n imaginary part= ");
scanf("%f",&c1.i);
printf("enter the 2nd complex
number:");
printf("\n real part= ");
scanf("%f",&c2.r);
printf("\n imaginary part= ");
scanf("%f",&c2.i);



Here, we will take two complex numbers from the user, and we ask them to type the real part and imaginary part of both complex numbers and read the values using structure pointers.

## Step 4

• the real part of both complex numbers
• the imaginary part of both complex numbers
res.r=c1.r+c2.r;
res.i=c1.i+c2.i;


Here, we add the real part of both complex numbers and assign that value to result in summation r. Similarly, we add the imaginary part of both complex numbers and assign that value to result in summation i.

## Step 5

Now, we print the output. The output will be in the format of res.r + res.i (i):

 printf("the sum of both complex
numbers is:\n");
printf("%f + %fi",res.r,res.i);



## Code

#include<stdio.h>
struct Comp{
float r;
float i;
}c1,c2,res;
int main(){
printf("enter the 1st complex number:");
c1.r = 5;
c1.i = 6;
c2.r = 12;
c2.i = 11;
res.r=c1.r+c2.r;
res.i=c1.i+c2.i;
printf("\ncomplex number 1:\t %f +%fi",c1.r,c1.i);
printf("\ncomplex number 2: \t %f +%fi",c2.r,c2.i);
printf("\nthe sum of both complex numbers is:\n");
printf("%f + %fi",res.r,res.i);
}

RELATED TAGS

c
communitycreator

CONTRIBUTOR

Srivasthavi Mannepula
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time