Saturday, May 9, 2009

Using a for loop how to display the names of planets in order using the enum type in programming language C++?

If you define the enumerated values in the order you want, it's easy. Here's a not-so-clever example of what you might do:





#include %26lt;iostream%26gt;





using namespace std;





enum NUMS { BEGIN=0, ONE, TWO, THREE, END };





int main(int argc, char *argv[]) {


for (int i = BEGIN; i %26lt; END; i++) {


switch (i) {


case ONE: cout %26lt;%26lt; "1 "; break;


case TWO: cout %26lt;%26lt; "2 "; break;


case THREE: cout %26lt;%26lt; "3 "; break;


default: break;


}


}


cout %26lt;%26lt; endl;


return 0;


}





A better solution would be one that didn't depend on the enum being defined in the right order, and didn't have hardcoded names in the switch statement to associate the names to the enum values. You'll need to be more creative for that, but for what you're looking for today, the above code will probably suffice.

flower pots

No comments:

Post a Comment