Loop & variable name suggestions?

Hi fellow Arduinoers,

I'm trying to write a simple loop to create a variable name related to the number of the loop iteration, but I am having some trouble. Basically, what I'm trying to do is have a loop that runs 3 times. Each time it runs, it will generate a name for a variable (e.g.: "name0001"), and I want it to add text into this variable (e.g.: Hello 0001"). The process is repeated 2 more times, with the numbers changing to 0002 and 0003.

Does anyone have any ideas on how I could change this loop so that it can do this?

void setup() {
  Serial.begin(9600);

  int counter = 1;
  int lines = 3;
  while(counter < (lines + 1)){

    char counter_char[10];  //convert current value of the counter to a char
    sprintf(counter_char,"%04d",counter);    // here, I get something like 0001, 0002, 0003, etc.

    char var_name[10];
    sprintf(var_name, "name%s", counter_char);  // name0001    - we want to use this as our variable name
    //Serial.println(var_name);


////////////////////////////////////////
// Is there a way to turn this section into a loop so that it creates variables "name0001", "name0002", and "name0003" so that
// they contain "Hello 0001", "Hello 0002", and "Hello 0003", respectively?
////////////////////////////////////////
     // Build variable with the corresponding name AND corresponding contents
     char name0001[50];
     strcpy (name0001, "");    
     strcat (name0001, "Hello ");
     strcat (name0001, counter_char);
     Serial.println(name0001);
     
     
     
/*
     char name0002[50];
     strcpy (name0002, "");    
     strcat (name0002, "Hello");
     strcat (name0002, counter_char);
     Serial.println(name0002);
     
     char name0003[50];
     strcpy (name0003, "");    
     strcat (name0003, "Hello");
     strcat (name0003, counter_char);
     Serial.println(name0003);    
*/

////////////////////////////////////////


    counter++;  //add a number to the counter and repeat again   
  }  
}



void loop() {
  // put your main code here, to run repeatedly: 

}

Hello :slight_smile:

Use an array!

Like guix said: Use an array. Will be much more easy even for fill.

To do what you want (and I want it to add text into this variable), you can use this code:

#define COUNT 3

char variables[COUNT][50];

void setup() {
  Serial.begin(9600);
  
  for (int i=0; i<COUNT; i++) {
     sprintf(variables[i], "Hello %04d", i+1);
     Serial.println(variables[i]);
  }
}

void loop() {}

Hi guix and luisilva,

thank you so much for your response! Of course... your suggestion of using an array makes total sense... Luis, the code you provided was incredibly helpful & helped illustrate how it all works. Thank you so much again! :slight_smile: