-3

Our teacher wants us to write a program that reverses the order of a character array. So like if the user inputs "hello", the program will output "olleh".

Here's the function that we were given:

void reverse_string(char coolstring[11], char newcoolstring[11])
{
    int count = 0, count2 = 0;

    while(coolstring[count] != '\0')
    {
        count++;
    }
    count -= 1;

    cout << coolstring[count];
    system("pause");

    while(coolstring[count] != 0)
    {
        newcoolstring[count] = coolstring[count2];
        count -= 1;
        count2 += 1;
    }   
}

but it doesn't work and I can't find out why while trying to make it work. Could you point me to the right direction?

Any help would be appreciated

LihO
  • 41,190
  • 11
  • 99
  • 167
user2225875
  • 1
  • 1
  • 1

2 Answers2

3

This is something you should solve on your own, but here's something that could point you to the right direction:

Let's say that coolstring looks like this:

 0  |  1  |  2  |  3  |  4  |  5
'h' | 'e' | 'l' | 'l' | 'o' | '\0'

This loop will retrieve the size of this string:

while(coolstring[count] != '\0')
    count++;

but since you want to use count as an index and count is equal to 5 in this case, you don't want to copy terminating ('\0') character so you should start with coolstring[4] at first (that's the point of outputting coolstring[count] after count has been decremented after the while loop... to make you realize that it is 'o').

Now look at this code:

while(coolstring[count] != '\0')
{
    newcoolstring[count] = coolstring[count2];
    count--;
    count2++;
} 

and just ask yourself these questions:

  1. when will be the coolstring[count] equal to '\0' when we start with 'o' and decrement count?
  2. how will newcoolstring look after this loop?
LihO
  • 41,190
  • 11
  • 99
  • 167
0

I think we need a more specific description of how it's not working. What inputs have you tried with, and what kind of wrong behavior do you get?

Just from your example, maybe the error is that you are only able to display the very last letter of your original string. That's because you have a cout statement to do that, just before the line system("pause"). Do you display the output string anywhere else?

maditya
  • 8,626
  • 2
  • 28
  • 28