Sunday 23 August 2015

Print numbers from 0 to n recursively

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

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


Following is the junit test case.

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class PrintNumbersTest {

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


No comments:

Post a Comment