Program to represent complex numbers and adding them

class ComplexNumber {
 int r=0;
 int i=0;
 String c;
 ComplexNumber(int r,int i){
  this.r=r;
  this.i=i;
  if(i>=0)
   c=""+r+"+"+i+"i";
  else
   c=""+r+i+"i";
 }
 public String toString(){
  return c;
 }
 public ComplexNumber add(ComplexNumber c){
  int r=this.r+c.r;
  int i=this.i+c.i;
  return new ComplexNumber(r,i);
 }
}
class Complex{
 public static void main(String ar[]) {
  ComplexNumber c1=new ComplexNumber(2,3);
  ComplexNumber c2=new ComplexNumber(1,-2);
  ComplexNumber c3=c1.add(c2);
  System.out.println(c1);
  System.out.println(c2);
  System.out.println(c3);
 }
}

No comments:

Popular Posts