Saturday, 4 May 2013

Add complex numbers,suntract complex numbers and multiply complex numbers and return the resultant complex number


A complex number is represented by two parts, real and imaginary part. Consider the complex number ‘ 
a + bi’ where ‘a’ is the real part and ‘b’ is the imaginary part. Also  i = 1 Consider the following struct:




#include<stdio.h>
//#include<math.h>
struct comp {
    float real;
    float img;
};
struct comp a1,a2;
struct comp sum_complex(struct comp a1,struct comp a2)
{
    struct comp sum;
    sum.real=a1.real+a2.real;
    sum.img=a1.img+a2.img;

return sum;
}
struct comp a1,a2;
struct comp multiply_complex(struct comp a1,struct comp a2)
{
    struct comp multiply;
    multiply.real=a1.real*a2.real;
    multiply.img=a1.img*a2.img;

return multiply;
}
struct comp a1,a2;
struct comp subtraction_complex(struct comp a1,struct comp a2)
{
    struct comp subtraction;
    subtraction.real=a1.real - a2.real;
    subtraction.img=a1.img - a2.img;

return subtraction;
}

void main(){
    struct comp add;
    struct comp multi;
    struct comp sub;
    printf("enter the complex no 1\n");
    scanf("%f",&a1.real);
    scanf("%f",&a1.img);
    printf("enter the complex no 2\n");
    scanf("%f",&a2.real);
    scanf("%f",&a2.img);
    add = sum_complex(a1,a2);
    sub =subtraction_complex(a1,a2);
    multi= multiply_complex(a1,a2);

    printf("The sum is            =   (%.2f) +(%.2f)i\n\n\n",add.real,add.img);
    printf("The subtraction  is   =   (%.2f) +(%.2f)i\n\n\n",sub.real,sub.img);
    printf("The multiplication is =   (%.2f) + (%.2f)i\n\n\n",multi.real,multi.img);

}





Input
This function should take a pointer of type complex as parameter and take input for real and imaginary parts of the complex number from the user.

Add
This function takes two parameters of type complex, perform complex number addition and return the resultant complex number. If we have two complex numbers (a+bi) and (c+di) then
(a+ib) + (c+id) = (a+c) + (b+d)i
e.g (2 + (-6)i) + (-4+2i) = -2 – 4i

            Subtract
This function takes two parameters of type complex, perform complex number subtraction and return the resultant complex number. If we have two complex numbers (a+ib) and (c+id) then
(a+ib) - (c+id) = (a-c) + (b-d)i
e.g (2 + (-6)i) - (-4+2i) = 6 – 8i

            Multiply
This function takes two parameters of type complex, perform complex number multiplication and return the resultant complex number. If we have two complex numbers (a+ib) and (c+id) then
(a+ib)*(c+id) = (ac-bd) + (bc+ad)i
e.g (2+6i) + (-4+2i) = (-8-12) + (-24+4)i
                                = -20 + (-20)i


No comments:

Post a Comment