How to center a string-Programing a Christmas Tree

Hi, I'm taking my first steps programing in Arduino and I would want to know if there's any function to program the posición of the text that prints in the console.
Basically I have to "draw" a Christmas Tree with "*". I already programed half of the tree and it was prety easy but I dont know how to center strings or even if its posible. Does anyone have an idea of how can I do it?

Here I post graphic examples of what I did and what I want to achieve in case I haven't explained well.
This is the half tree I already did:
*
**



And this is what I want to do now:
*




Any suggestion would be appreciated. Thanks!!

I already programed half of the tree and it was prety easy

Please post the code that you have so far

You first need to know the width of the bottommost row.

Hi,
Welcome to the forum.

Please read the post at the start of any forum , entitled "How to use this Forum".
OR
http://forum.arduino.cc/index.php/topic,148850.0.html.
Then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Thanks.. Tom... :slight_smile:

spicyshark:
Hi, I’m taking my first steps programing in Arduino and I would want to know if there’s any function to program the posición of the text that prints in the console.
Basically I have to “draw” a Christmas Tree with “*”. I already programed half of the tree and it was prety easy but I dont know how to center strings or even if its posible. Does anyone have an idea of how can I do it?

Here I post graphic examples of what I did and what I want to achieve in case I haven’t explained well.
This is the half tree I already did:
*
**



And this is what I want to do now:
*




Any suggestion would be appreciated. Thanks!!

Something like this maybe…

void setup() {

  Serial.begin(115200);

  int total_stars = 9; // maximum number of stars in string (must be odd)
  int star_pos = total_stars / 2; //initialise to middle of string

  char star_str[total_stars + 1]; //declare string array. +1 to add null terminator

  memset (star_str, ' ', total_stars); //initialise array to with <space>
  star_str[total_stars] = '\0'; //add null terminator

  //build christmas tree
  for (int i = 0; i < total_stars; ++i) {
    if (i % 2 == 0) {
      star_str[star_pos] = '*';
      star_str[star_pos + i] = '*';
      --star_pos;
      Serial.print(star_str); //print out char string
    }
    Serial.print("\n");
  }

}

void loop() {

}

Output:

    *

   ***

  *****

 *******

*********

hope the helps…

Why complicate things ?

void setup()
{
  Serial.begin(115200);
  Serial.println("    *\n   ***\n  *****\n *******\n*********");
}

void loop()
{
}

However, I assume that the OP has not given us the full story of what he/she is trying to achieve

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.