Friday, 20 December 2013

Program 1: Logical Sequecial numbers in a Traigular form

This is the program for printing the numbers in the below format:

1
3*2
4*5*6
10*9*8*7
11*12*13*14*15


Method 1:

public void printFormat1(){
        int num = 10;
        for(int i = 1; i <= num; i++){
            System.out.println(formString("",getStartNum(i),i,(i%2 == 0 ? -1 : 1)));
        }
    }
    
    public int getStartNum(int num){
        int incrRdecr = num%2 == 0 ? -1 : 1;
        int sum = (num * (num+1))/2;        
        if(incrRdecr == 1){
            return sum - num + 1;
        }else{
            return sum;
        }        
    }
    
    public String formString(String str, int startNum, 
            int countNum, int incrCount){
        String resp;
        if(countNum == 0){
            str = (str + startNum);
            resp = str.substring(0, str.lastIndexOf("*"));
            return resp;
        }else{
            resp = formString(str + startNum + "*",(startNum + incrCount),--countNum, incrCount);
            return resp;
        }        
    }