Sunday, 23 August 2015

Print numbers from n to 0 recursively

Print(5) = “5,4,3,2,1,0”
Print(-5) = “-5,-4,-3,-2,-1,0”
public class PrintNumbers {

 public static String getNumbers(int n){
  if(n==0)
   return ""+0;
  if(n > 0)
   return n + "," + getNumbers(--n);
  return n + "," + getNumbers(++n);
 }
}


Following is the junit test case for above program.

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class PrintNumbersTest {

 @Test
 public void test1(){
  assertTrue(PrintNumbers.getNumbers(5).equals("5,4,3,2,1,0"));
  assertTrue(PrintNumbers.getNumbers(-5).equals("-5,-4,-3,-2,-1,0"));
  assertTrue(PrintNumbers.getNumbers(-1).equals("-1,0"));
  assertTrue(PrintNumbers.getNumbers(1).equals("1,0"));
 }
}


No comments:

Post a Comment