Hey guys, thx for the time you spent clicking here :D

My question is simple enough. Let me give a basic example though:

char a1[]="ok";
char a2[]="yes";
char a3[]="right";
for (int n=1;n<=3;n++;)
    cout << a<n>;

Is there some way to make this concept work?

Any help much appreciated!

5 Years
Discussion Span
Last Post by Ancient Dragon

I don't think so this can be implemented. Perhapes this may be close to what you want.

You can do something like this using 2 dimensional array. Here is a code snippet.

char a[][7]={"ok","yes","right"};

    for(int i=0; i<3; i++)
        for(int j=0 ; j<7 ; j++)
          cout<< a[i][j];

i think he wants to know that if there is a way to output variables with a loop statement which contains only one instruction whithin the brackets like this:

int age = 32;
char name[50] = "Pickatchu";
double height = "1.65";

for(int i = 0; i < 3; i++)
    cout << ..... << endl;

something instead of "....." to output:


the simple answer is no
there is altho a way aroud this but is too unconvinient(overhead)


The way to make the concept work is to use an array instead of individual variable names. If the program already has individual variable names then to use a loop you could create an array of pointers that point to each of the individual variables, something like this:

char a1[]="ok";
char a2[]="yes";
char a3[]="right";
char* names[] = {a1,a2,a3,NULL};
for (int n = 0; names[n] != NULL;n++;)
    cout << names[n] << '\n';

Edited by Ancient Dragon

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.