ADVERTISEMENT
ADVERTISEMENT

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:

        *
       ***
      *****
     *******
       ***
      *****
     *******
    *********
      *****
     *******
    *********
   ***********
     *******
    *********
   ***********
  *************
        *
        *
     *******
ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.