Home »
Code Snippets »
C/C++ Code Snippets
C program to print Christmas tree using stars and special characters
This program is asked by Sam Atkinson Amerity through comment on 18/12/2016.
Question
Do you know how to make a christmas tree in c with code block ?? i need help and also logic explanation :)
Answer
There may be many type of Christmas tree art using special character, I created the following one
<&&>
<*@**>
<*%%00*>
<0@&&&%@@>
<@%@@*&*%@@>
<@0%@%@@%%*@&>
<0%0*0*@&*%*&&0>
<@%@%&%&0**0*@00%>
<@*&@0***%&%@@0*@@*>
<@&0000&&&0%000&@%@@&>
#@%0#
#%&0#
#*&0#
#@*0#
Here is the program (In this program I run a loop till 10 rows to create tree branches and print random characters from given 5 characters using srand() and rand() library functions) there are two fixed characters at beginning (<) and end (<) of each line so that tree looks like good.
After printing the branches on the tree, I tried to create rest of the part of the tree by printing random characters (number of character will be printed 3 between two # characters).
In both loops I put some spaces according to need.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i,j,randomPos;
char charSet[]={'@','0','%','*','&'};
int space=10;
srand(time(NULL));
for(i=1;i<=10;i++)
{
//print space
for(j=0;j<space;j++)
printf(" ");
printf("%c",'<');
for(j=0;j<(i*2);j++)
{
randomPos=rand()%5;
printf("%c",charSet[randomPos]);
}
printf("%c",'>');
printf("\n");
space--;
}
//another loop set
space=9;
for(i=1;i<5;i++)
{
for(j=0;j<space;j++)
printf(" ");
printf("#");
for(j=0;j<3;j++)
{
randomPos=rand()%5;
printf("%c",charSet[randomPos]);
}
printf("#");
printf("\n");
}
return 0;
}
Output
<&&>
<*@**>
<*%%00*>
<0@&&&%@@>
<@%@@*&*%@@>
<@0%@%@@%%*@&>
<0%0*0*@&*%*&&0>
<@%@%&%&0**0*@00%>
<@*&@0***%&%@@0*@@*>
<@&0000&&&0%000&@%@@&>
#@%0#
#%&0#
#*&0#
#@*0#