How to display a String or word based on a number output


I am trying to find a way to display a text definition of a state rather than a number. e.g. if a variable is at "0" i can easily display this on a display, simply by displaying that variable, but I would like to display a variable value of 0 as "State1" and 1 as "State2" etc on screen.

Any help on how to accomplish this would be greatly appreciated!


Put the strings in an array and use the number as the index to the array to pick which one to display.

Thanks for the reply - I'm a beginner - is there a guide to setting up arrays?

Google "C++ arrays" and read for a while. You'll see what I mean.

Thanks - so I've read through that and am using the following in the void setup:

int foo[3] = {0, 1, 2};

I have the below in the void loop


but get the error "'foo' was not declared in this scope" - error below:



exit status 1
'foo' was not declared in this scope

Any pointers on what I'm doing wrong? I just want a value of 1 to be displayed as "B"

Several things.

First, google "C++ scope" and read up on that. Any variables you define inside setup are not available inside loop.

Secondly, look in the reference on this site at all the variable types. An int is a number. "A" is a string. You can't put a string in an int. You could put the ascii code for a single character in an int (although char would make a lot more sense) but then you'd say 'A' instead of "A".

Lastly, when you're looking for help post the whole code. Use code tags. If you don't know what code tags are then read the "How to Use This Forum" post on any board here. There's not a lot of debugging we can help with if we've only got one line and no context.

Do as Delta_G suggests and also answer the questions in the code below. The post by Nick Gammon at the top of this Forum has topics that will help you answer the questions posed.

char *states[] = {"Indiana", "Nebraska", "Ohio"};   // Why are these defined here?

void setup() {
  Serial.println("Enter a number 1 - 3:");

void loop() {

  int whichOne;

  if (Serial.available() > 0) {                       // What does the available() method do?
    whichOne = - '0';                   // What does this do?
    Serial.print("You entered: ");
    if (whichOne < 1 || whichOne > 3) {               // Why do this?
      Serial.println("Must be 1, 2, or 3");
    } else {
      ShowTheState(whichOne - 1);                     // Why - 1?
      Serial.println("Enter another number 1 - 3:");

  Purpose: To display the state selected

  Parameter list;
    int selected    The index number for the state selected

  Return value:

void ShowTheState(int selected)

Thanks so much! Cracked it.