Tuesday, October 13, 2015

Adding 2 numbers using Java

Let us have fun to add two numbers in variety of ways :

public class FunWithAdd {
   private int num1;
   private int num2;
  public FunWithAdd(int num1, int num2){
       this.num1=num1;
       this.num2=num2;
   }
   public int getNum1(){
       return num1;
   }
    public int getNum2(){
       return num2;
   }
    public void setNum1(int num1){
        this.num1=num1;
    }
    public void setNum2(int num2){
        this.num2=num2;
    }
   int sum(){
       return num1+num2;
   }
   int sum(int n1, int n2){
       return n1+n2;
   }
   int sumWithItr (int n1, int n2){
      int s=n1;
     
      for(int i=1;i<=n2;i++){
          s++;
      }
      return s;
   }
   int sumRecursive(int n1, int n2){
        if (n2 ==0){
            return n1;
        }
        return sumRecursive(++n1,--n2);
      }
   }

Create a class to test variety of sum methods.

public class Add2Nums {
    public static void main(String[] args) {
        /* Summing Locals */
        int num1=25;
        int num2=12;
        System.out.println("sum : "+(num1+num2));
        /* Sum using Object of FunWithAdd*/
        FunWithAdd numsObject= new FunWithAdd(30,60);
        System.out.println("Adding the numbers in Object : "+numsObject.sum());
        System.out.println("Adding the numbers in Object by sending data from outside :"+numsObject.sum(19,20));
        numsObject.setNum1(7);
        numsObject.setNum2(9);
        System.out.println("sum using sumWithItr method : "  +numsObject.sumWithItr(numsObject.getNum1(),numsObject.getNum2()));
         numsObject.setNum1(43);
        numsObject.setNum2(2);
        System.out.println("sum using sumRecursive: "+numsObject.sumRecursive(numsObject.getNum1(),numsObject.getNum2()));
    }
}

Output :
sum : 37
Adding the numbers in Object : 90
Adding the numbers in Object by sending data from outside :39
sum using sumWithItr method : 16
sum using sumRecursive: 45

Change the values and have fun… :)
©Nancy : created at 2:07 am IST

No comments:

Post a Comment