That is what we're here for :)
The next thing to do is get rid of the number 10. Here we have a number that represents the amount of elements in an array. We even use the number 9, because that is one less than the amount of elements. If you want to change the amount of elements in the array, your going to have to remember which 10s need to be changed. If your program was large enough, it might be tricky to remember that the 9 is related to the 10 at all.
These are called "magic numbers", and they are bad.
One thing you can do is declare a constant:
1 2 3 4 5 6 7
|
const int size = 10;
string forwardNames[ size ] = { /* ... */ };
string backwardsNames[ size ];
for ( int i = 0; i < size; ++i )
backwardsNames[i] = forwardNames[ size - 1 - index ];
|
Now, if you wanted to change the amount of elements in the array you just need to change
size
and adjust forwardNames accordingly.
However, even better is to learn the
sizeof
operator ( I think it is an operator ).
Anyway,
sizeof
is used to know, well, the size of something:
1 2 3
|
std::cout << sizeof( int ); // probably prints 4
std::cout << sizeof( char* ); // prints 4 or 8, depending upon 32 or 64 operating system
std::cout << sizeof( std::string ); // prints out 28 for me
|
Arrays also know their size:
1 2
|
std::string names[] = { "Fred", "Tuyet", "Annie", "Moe", "Ria", "Luke", "Jim", "May", "Rex", "Omar" }; // notice I didn't declare the size of the array
std::cout << sizeof( names ); // prints 280 for me
|
Arrays declared and initialized like this must have at least one element in them. With that in mind, the length of an array can be found via:
1 2 3 4 5 6
|
std::string names[] = { "Fred", "Tuyet", "Annie", "Moe", "Ria", "Luke", "Jim", "May", "Rex", "Omar" };
const int size = sizeof( names ) / sizeof( names[0] ); // size = 10
std::string otherNames[ size ];
for ( int i = 0; i < size; ++i )
// whatever
|
Edit, you also may notice I use
std::
. This is the preferred method. Basically, namespaces create a scope, and by saying
using namespace std;
you remove that scope and thus remove the whole purpose of namespace in the first place:
Bad
1 2 3 4 5 6 7
|
#include <iostream>
using namespace std;
int main( void )
{
cout << "hello\n";
}
|
Good
1 2 3 4 5 6
|
#include <iostream>
int main( void )
{
std::cout << "hello\n";
}
|