Program to Print Christmas Tree Character Pattern
In this article we are going to see how to print the Christmas tree pattern.
Example-2:
When height Of Tree value=5
A
B B
C C C
D D D D
E E E E E
| |
| |
| |
| |
Now, let’s see the actual program to print it.
Approach:
- Enter the height of the Christmas tree in an integer variable
heightOfTree. - Take first for loop to print the full height of the tree.
- Take second/inner for loop to print the column values (i.e. characters and spaces).
- Then use another for loop for the lower part of the tree.
Java Code to Print Christmas Tree Character Pattern
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int ascii=64;
Scanner scan = new Scanner(System.in);
System.out.print("Height Of The Christmas Tree : ");
//Taking height Of Tree as input from user
int heightOfTree=scan.nextInt();
//Outer loop for the upper part of the tree
for(int r = 1;r<=heightOfTree;r++)
{
for(int c = heightOfTree-r; c > 0; c--)
//Inner loop to print the spaces
System.out.print(" ");
for(int d = 1;d<=r;d++)
//Inner loop to print the stars
System.out.print((char)(r+ascii)+" ");
//Prints a new line
System.out.println("");
}
//Second outer loop to print the lower part of the tree
for(int r = 1; r<=heightOfTree-1;r++)
{
System.out.print(" ");
for(int c = heightOfTree -3;c>0;c--)
//Inner loop that prints spaces
System.out.print(" ");
for(int d = 2;d>0;d--)
//Inner loop that prints the straight lines
System.out.print("| ");
//Prints a new line
System.out.println();
}
}
}
Output:
Height Of The Christmas Tree : 5
A
B B
C C C
D D D D
E E E E E
| |
| |
| |
| |
Are you seeking professional help for coding in the Java programming language? The tutorial of Java Programming Examples for beginners and experts will strongly improve your coding skills then you can program for any logic in Java.
Related Java Character Pattern Programs: