Tuesday 10 July 2012

Calculate Complex Numbers in C


#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

struct complex
{
      int real;
      int img;
};

void main()
{
  int choice;
  struct complex a, b, c;

  while(1)
  {
       printf("Press 1 to add two complex numbers.\n");
       printf("Press 2 to difference two complex numbers.\n");
       printf("Press 3 to product two complex numbers.\n");
       printf("Press 4 to exit.\n");
       printf("Enter your choice ");
       scanf("%d",&choice);

    if( choice == 4)
      return;

    if(choice >= 1 && choice <= 3)
    {
         printf("Enter a and b and a + ib is the 1st complex number.");
       printf("\na = ");
       scanf("%d", &a.real);
       printf("b = ");
      scanf("%d", &a.img);
      printf("Enter c and d and c + id is the 2nd complex number.");
    printf("\nc = ");
      scanf("%d", &b.real);
         printf("d = ");
         scanf("%d", &b.img);
    }


// add two complex numbers
    if ( choice == 1 )
    {
     c.real = a.real + b.real;
      c.img = a.img + b.img;
printf("Summation of two complex numbers = %d + %di",c.real,c.img);
     
    }




// Subtract tow complex numbers
    else if ( choice == 2 )
    {
      c.real = a.real - b.real;
      c.img = a.img - b.img;

      if ( c.img >= 0 )
       printf("Subt of two complex numbers = %d + %di",c.real,c.img);
   
    }




// multiply two complex numbers
    else if ( choice == 3 )
    {
       c.real = a.real*b.real - a.img*b.img;
    c.img = a.img*b.real + a.real*b.img;
printf("product of two complex numbers = %d + %di",c.real,c.img);
   
    }



    printf("\n\nPress any key to enter choice again\n");
  }
getche();
}

No comments:

Post a Comment