// the string is given by the user, so we define a fixed array of char
// there are other, more refined, ways of doing this, but we'll keep it simple!
char my_array[30];
cout << "enter a string: ";
cin >> my_array;
// now we get the length of the string in the array (using the length
// of the array is an obvious mistake to make - it would work up to a
// point - only we'd print out gibberish once we went past the end
// of the string).
int length_of_my_string = strlen(my_array);
// now loop and print out the array element for even values
// note that we _could_ just increment the loop counter twice for
// each loop, but then we'd need to be on our guard against
// exceeding the end-of-string.
for (int count=0; count<length_of_my_string; count++)
{
// check if count is even, if so print my_array[i]
if ( count%2 == 0 ) // "%" is the modulus operator
cout << my_array[count];
}
// and just to show what using the size of the array instead of the
// string would do;
cout << "\n\n"; // don't want output of both loops on the same line!
length_of_my_string = sizeof my_array; // this is where it all goes horribly wrong!
for (int count=0; count<length_of_my_string; count++)
{
// check if count is even, if so print my_array[i]
if ( count%2 == 0) // "%" is the modulus operator
cout << my_array[count];
}
A better and faster way to do it would be to use 'count += 2' instead of 'count++', and then you don't need the modulus to check if it's even. This will only loop half as many times, which will be quite a speed increase in large applications with long strings.