Source:
#include <stdio.h>
void main()
{
int i, j, tree_Size, spaces, total_Spaces, x;
char tree_Characters;
printf("Enter characters to use --> ");
scanf("%c", &tree_Characters);
printf("Enter size of tree --> ");
scanf("%d", &tree_Size);
//For handling top part of tree
for (i = 0; i <= tree_Size; i++) {
printf("\n");
total_Spaces = tree_Size - i;
//Determine spaces before each number for pyramid
for (spaces = 1; spaces <= total_Spaces; spaces++)
printf(" ");
//Make first line always one number
for (j = -1; j < i; j++)
if (j <= -1)
printf("%c", tree_Characters);
else if (j > -1)
printf("%c%c", tree_Characters, tree_Characters);
}
//For handling stem and base of tree
for (i = 0; i <= tree_Size; i++) {
//if handling stem
if (i < tree_Size) {
printf("\n");
for (spaces = 1; spaces <= tree_Size; spaces++)
printf(" ");
printf("%c", tree_Characters);
}
//else if handling base
else if (i == tree_Size) {
printf("\n");
for (x = 0; x <= tree_Size * 2; x++) {
printf("%c", tree_Characters);
}
}
}
printf("\n");
}
Here is the output it produces so far
Here is a thread I made on reddit for better understanding (comments)
The goal of the assignment is for it to look like this:
*** Print a Tree ***
Enter characters to use --- *|=+
Enter size of tree --- 4
*
***
*****
*******
*********
|
|
|
|
====+====
What I don’t understand is how to process characters. The teacher was mentioning putting characters into some buffer and then clearing it etc, I have no idea. Can anyone help? I have to use scanf, can’t convert anything to strings or use anything advanced.
You need to make
tree_Charactersa array (char tree_Characters[5]for a five element array, which will hold your four tree chars and a nul terminator), and change the first scanf.See http://linux.die.net/man/3/scanf for more information.
Edit: You will of course have to change the rest of the program to select the appropriate characters for each tree element. (See @eznme’s answer.)
Edit: No-array Version:
This will react badly to too-short input lines.