Monday, July 31, 2017

Operations on complex numbers in C

#include<stdio.h>
struct cmplx
{
    float real;
    float img;
};
struct cmplx add(struct cmplx x, struct cmplx y)
{
    struct cmplx z;
    z.real = x.real + y.real;
    z.img = x.img + y.img;
    return(z);
}
struct cmplx sub(struct cmplx x, struct cmplx y)
{
    struct cmplx z;
    z.real = x.real - y.real;
    z.img = x.img - y.img;
    return(z);
}
struct cmplx mul(struct cmplx x, struct cmplx y)
{
    struct cmplx z;
    z.real = x.real * y.real- x.img * y.img;
    z.img = x.real * y.img + x.img * y.real;
    return(z);
}
struct cmplx div(struct cmplx x, struct cmplx y)
{
    struct cmplx z;
    z.real = (x.real*y.real+x.img*y.img)/(y.real*y.real+y.img*y.img);
    z.img = (y.real*x.img-y.img*x.real)/(y.real*y.real+y.img*y.img);
    return(z);
}
void main()
{
    struct cmplx c1,c2,c3;
    char ch;
    printf("Enter the operator +,-,*,/ : ");
    ch = getchar();
    printf("\nEnter the real part of fist complex number : ");
    scanf("%f",&c1.real);
    printf("\nEnter the imaginary part of fist complex number : ");
    scanf("%f",&c1.img);
    printf("\nEnter the real part of 2nd complex number : ");
    scanf("%f",&c2.real);
    printf("\nEnter the imaginary part of 2nd complex number : ");
    scanf("%f",&c2.img);
    switch(ch)
    {
        case '+':
        {
            c3=add(c1,c2);
            break;
        }
        case '-':
        {
            c3=sub(c1,c2);
            break;
        }
        case '*':
        {
            c3=mul(c1,c2);
            break;
        }
        case '/':
        {
            c3=div(c1,c2);
            break;
        }
        default:
        {
            printf("Invalid operator....\a");
            break;
        }
    }
    printf("\n\nThe result is %f + %fi",c3.real,c3.img);
}

Related Posts:

  • Count no. of words in a sentence in C#include<stdio.h> void main() {     char str[50],i,wordcount=0;     printf("Enter a line of text : ");     gets(str);     for(i=0;str[i]!='\0';i++)     {     &… Read More
  • Copying string 2 to string 1#include<stdio.h> void copystr(char [],char []); void main() {     char str1[50],str2[50];     printf("Enter 1st string,str1 : ");     gets(str1);     printf("\nEnter 2nd string,s… Read More
  • Code in C to multiply two matrix#include<stdio.h> void matmultiply(int m[3][3], int n[3][3]); void read(int x[3][3]); //void read2(int y[3][3]); void main() {     int a[3][3],b[3][3],l,w;     printf("\nFor matrix a :-\n");   &… Read More
  • Concatenation of two string in C#include<stdio.h> void catstr(char [],char []); void main() {     char str1[50],str2[50];     printf("Enter 1st string (str1) :");     gets(str1);     printf("\nEnter 2nd string (… Read More
  • Sorting names in C#include<stdio.h> //#include<string.h> void copystring(char txt1[], char txt2[]) {     int k;     for(k=0;txt2[k]!='\0';k++)     {         txt1[k]=txt2[k];  … Read More

0 comments:

Post a Comment