Home »
Java Programs »
Java Basic Programs
Java program to print Christmas tree
In this java program, we are going to learn how to print a Christmas tree? By using nested looping and basic concept, we are printing the tree using stars.
Submitted by IncludeHelp, on November 02, 2017
Example:
*
***
*****
*******
***
*****
*******
*********
*****
*******
*********
***********
*******
*********
***********
*************
*
*
*******
Program to print Christmas tree in java
public class ChristmasTree
{
public static final int SEGMENTS = 4;
public static final int HEIGHT = 4;
public static void main(String[] args)
{
makeTree();
}
public static void makeTree()
{
int maxStars = 2*HEIGHT+2*SEGMENTS-3;
String maxStr = "";
for (int len=0; len < maxStars; len++)
{
maxStr+=" ";
}
for (int i=1; i <= SEGMENTS; i++)
{
for (int line=1; line <= HEIGHT; line++)
{
String starStr = "";
for (int j=1; j <= 2*line+2*i-3; j++)
{
starStr+="*";
}
for (int space=0; space <= maxStars-(HEIGHT+line+i); space++)
{
starStr = " " + starStr;
}
System.out.println(starStr);
}
}
for (int i=0; i <= maxStars/2;i++)
{
System.out.print(" ");
}
System.out.print("*\n");
for (int i=0; i <= maxStars/2;i++)
{
System.out.print(" ");
}
System.out.print("*\n");
for(int i=0; i <= maxStars/2-3;i++)
{
System.out.print(" ");
}
System.out.print("*******\n");
}
}
Output
*
***
*****
*******
***
*****
*******
*********
*****
*******
*********
***********
*******
*********
***********
*************
*
*
*******
Java Basic Programs »