Write a C program to find addition, subtraction, multiplication and division of two complex numbers.
/* mutiply two complex numbers */
void multiplyComplex(int num1[2], int num2[2], int num3[2]) {
num3[0] = (num1[0] * num2[0]) + (-1 * num1[1] * num2[1]);
num3[1] = (num1[1] * num2[0]) + (num1[0] * num2[1]);
return;
}
/* division of two complex numbers */
void divideComplex(int num1[2], int num2[2]) {
int val1[2], val2[2];
val1[0] = num2[0];
val1[1] = -1 * num2[1];
printf("Division Result:\n");
multiplyComplex(num1, val1, val2);
printf("(%d + (%di)) / ", val2[0], val2[1]);
multiplyComplex(num1, val1, val2);
printf("(%d + (%di))\n", val2[0], val2[1]);
return;
}
int main() {
int complex1[2], complex2[2], complex3[3], ch;
/* get the first complex number from the user */
printf("x+iy - First Complex number :");
scanf("%d%d", &complex1[0], &complex1[1]);
/* get the second complex number from the user */
printf("x+iy - Second complex number:");
scanf("%d%d", &complex2[0], &complex2[1]);
/* provide option for different operations */
printf("1. Addition\n2. Subtraction\n");
printf("3. Multiplication\n4. Division\n");
printf("Enter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
/* Add complex numbers */
complex3[0] = complex1[0] + complex2[0];
complex3[1] = complex1[1] + complex2[1];
printf("Addition Result:\n");
printf("%d + (%di)\n", complex3[0], complex3[1]);
break;
case 2:
/* subtract complex numbers */
complex3[0] = complex1[0] - complex2[0];
complex3[1] = complex1[1] - complex2[1];
printf("Subtraction Result:\n");
printf("%d + (%di)\n", complex3[0], complex3[1]);
break;
case 3:
/* multiply complex numbers */
multiplyComplex(complex1, complex2, complex3);
printf("Multiplication Result:\n");
printf("%d + (%di)\n", complex3[0], complex3[1]);
break;
case 4:
/* divide complex numbers */
divideComplex(complex1, complex2);
break;
default:
printf("Wrong option!!\n");
break;
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
x+iy - First Complex number :10 20
x+iy - Second complex number:30 40
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice:1
Addition Result:
40 + (60i)
x+iy - First Complex number :10 20
x+iy - Second complex number:30 40
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice:1
Addition Result:
40 + (60i)
No comments:
Post a Comment