Sunday, 23 August 2015

Draw triangle using recursion

Write a program to draw a triangle, which takes an integer as input and display the triangle like below.

getTriangle(2)
*
**

getTriangle(5)
*
**
***
****
*****
public class PrintTriangle {

 public static void getTriangle(int n) {
  if (n < 1)
   throw new IllegalArgumentException("Input must be a +ve integer");
  getTriangle1(n);
 }

 private static void getTriangle1(int n) {
  if (n == 1){
   System.out.println("*");
   return;
  }
  getTriangle1(n - 1);
  printStars(n);
  System.out.println();
 }

 private static void printStars(int n) {
  if (n == 0)
   return;
  System.out.print("*");
  printStars(--n);
 }
}

public class PrintTriangleTest {
 public static void main(String args[]){
  PrintTriangle.getTriangle(1);
  System.out.println("");
  PrintTriangle.getTriangle(2);
  System.out.println("");
  PrintTriangle.getTriangle(3);
  System.out.println("");
  PrintTriangle.getTriangle(4);
  System.out.println("");
  PrintTriangle.getTriangle(5);
 }
}


Output

*

*
**

*
**
***

*
**
***
****

*
**
***
****
*****


No comments:

Post a Comment