plz look at this code and tell me where I'm going wrong. I can't use another array to reverse the string.

const int MAX_SIZE = 15; // Max word size of word, allow for '\0' 
void reverse(char word[]);     // function prototype 
int main() { 
  char word[MAX_SIZE]; 
  cout << endl << "Enter a word : "; 
  cin >> word; 
  cout << "You entered the word \"" << word << "\"" << endl; 
  cout << "The word in reverse order is " << word << endl; 

    return 0; 
} // main 
void reverse(char word[]) { 
   // you can have local scalar variables of type int and char 
   // However, you cannot have any local array variables 
   // This function will reverse the characters in the array word 
    char ch;
    for(int i = 0, j = MAX_SIZE; i != j; i++, j--) {
            ch = word[j];
            if( (ch >= 'a' || ch >= 'A' ) && (ch <= 'z' || ch <= 'Z') )
            word[i] = ch;        

Recommended Answers

All 6 Replies

You don't want to start j one beyond the end of the array (very much like you said you fixed in your last thread), you want to start it at the end of the text. And it would be better to use <= instead of != (think of what may be missed if you have an even or odd number of characters). And you want to swap front-to-back.

i can't follow that code. we've just started with pointers, and i'm not supposed to use them on this example, but the next problem will require pointers.

i'm getting closer. world comes back as worow. here's what i got..

int a, b, i;    
    for(i = 0; word[i] != '\0'; i++) {
        a = i;    
        b = a;
    for(i = 0; i <= b; i++, a--) {
        word[i] = word[a];

This is not a swap:

word[i] = word[a];

And perhaps you mean i <= a as the condition:

for(i = 0; i <= b; i++, a--)

i'll think about that.......... thx

ch = word[a]
word[a] = word
word = ch

it works and i'm sure something like this only harder will be on the test. thx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.