Like Tree3Likes
  • 2 Post By Justin Page
  • 1 Post By laserlight

Need help in reversing words in an Array

This is a discussion on Need help in reversing words in an Array within the C Programming forums, part of the General Programming Boards category; Hello Everyone! I hate to ask this question as I feel it decrements myself from problem-solving a solution I'm working ...

  1. #1
    Registered User
    Join Date
    Jul 2012
    Posts
    3

    Need help in reversing words in an Array

    Hello Everyone!

    I hate to ask this question as I feel it decrements myself from problem-solving a solution I'm working on. Currently, I've written a program that has the capability of storing a sentence in an char array and then putting them out in reverse. For example:

    Enter Sentence: The Quick Brown Fox!
    Reversal of sentence: !xoF nworB kciuQ ehT

    Nevertheless, my goal is to create the program so that the reversal sentence will instead read "Fox Brown Quick The." Now I've attempted to problem solve through I've read on forums that in order to solve this you need to first reverse the whole string and then individually reverse the words in the array. However, I feel I have yet to reach sensible conclusion.

    I'm going to attach two files: the one one that gives the above result as well as an attempted try at switching the arrays in order to output, to what i believe, a logical result. I understand I am missing something key in this solution and therefore I would appreciate the help. I'm not asking for free handouts so I hope I don't anger anyone in asking for a little assistance in this problem.
    first attempt
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define SIZE 100
    
    int main (void)
    {
        char msg[SIZE], getLetter;
        int count = 0, len = 0, output;
    
        printf("Enter Sentence: ");
        getLetter = getchar();
        while (count < SIZE && getLetter != '\n')
        {
            msg[count] = getLetter;
            count++;
            len++;
            getLetter = getchar();
        }
        printf("Reversal of sentence: ");
        for (output = len - 1; output >= 0; output--)
        {
            putchar(msg[output]);
        }
        printf("\n\n");
    
        system("pause");
        return 0;
    }
    second attempt
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    #define SIZE 100
    #define HAND 100
    
    int main()
    {
        char msg[SIZE], temp[HAND], getLetter, holdLetter;
        int count = 0, len = 0, output, second_output;
    
        printf("Enter Sentence: ");
        getLetter = getchar();
        while (getLetter != '\n')
        {
            msg[count] = getLetter;
            count++;
            getLetter = getchar();
        }
        printf("Reversal of sentence: ");
        for (output = count - 1; output >= 0; output--)
        {
            holdLetter = msg[output];
            while (holdLetter != '\n')
            {
                if (holdLetter == ' ')
                {
                    for (second_output = len - 1; second_output >= 0; second_output--)
                        putchar(temp[second_output]);
                }
                else
                {
                    temp[len] = holdLetter;
                    len++;
                }
            }
        }
        system("pause");
        return 0;
    }

    Thank You for reading and have a wonderful day!CIS_161.cCIS_161.c
    Last edited by Justin Page; 07-20-2012 at 07:54 PM.

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,661
    You're second attempt is a lot closer to what needs to be done I think.

    This is a loop by itself:
    Code:
    while (getLetter != '\n');
    
    while (getLetter != '\n')
        /* do nothing */ ;
    Even after you fix that I think you need the '\n' to be part of the input, so put this after the end of that loop.
    Code:
    msg[count++] = getLetter;
    This is because of what happens later. The while loop inside of the for loop, on line 25 is the source of your next program hang. The next 'holdLetter' is never fetched within the loop, so the condition will never be false. That means the loop goes forever. I was able to confirm this by debugging. I entered "The quick brown fox" and the code kept copying xs. I think the outer for loop on line 22 is unnecessary then. You need to update the output variable in the while loop and get the next holdLetter.

    These fixes should at least get your current code doing something. Try the fixes and see if your program is otherwise correct.

  3. #3
    Registered User
    Join Date
    Mar 2010
    Posts
    535
    Welcome! Don't worry about people getting angry -- people here are generally happy to help so long as you help yourself by trying, and posting your attempts, which you have.

    Your code is really close to working.

    As whiteflags said, your program will loop forever because

    Code:
            while (holdLetter != '\n')
    will never be true.

    I'd be inclined to keep the outer (for) loop and get rid of this while loop. The output >= 0 condition in your for loop will terminate the reversal process once you get to the beginning of the string.

    After that you'll have a couple of other problems to iron out -- e.g. you don't print any spaces between your words. But I'll let you try to figure those out - you can always come back and ask for help again.

  4. #4
    Registered User
    Join Date
    Jul 2012
    Posts
    3

    Progress so far...

    Thank You so much for the helpful criticism! So far, I've deleted the second while statement and therefore it allows the program to run. However, I'm back to the issue of reversing the sentence to where I like it. As I was mentioning: "Quick Brown Fox!" converted to "Fox Brown Quick!" I've been able to figure out how to print the exclamation point at the end of the sentence but reversing the array has still proven difficult and therefore I still need help. For example:
    Enter Sentence: the quick brown fox!
    Reversal of sentence: foxbrownfoxquickbrownfox!
    Press any key to continue . . .

    It seems the reversal process is coming through slightly but I need further direction on how to make it so it comes out correctly. Thank you for the info on hinting to me that it won't print spaces. I believe it's because of my if(holdLetter == ' ') statement that prevents it from having spaces. Ultimately, if I can receive further directions that would be great! Thank you so much everyone I really do appreciate it =)

    Progress so Far
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define SIZE 100
    #define HAND 100
    
    int main()
    {
        char msg[SIZE], temp[HAND], getLetter, holdLetter, terminate;
        int count = 0, len = 0, output, second_output, ending;
    
        printf("Enter Sentence: ");
        getLetter = getchar();
        while (getLetter != '\n' && getLetter != '.' && getLetter != '?' && getLetter != '!')
        {
            msg[count] = getLetter;
            count++;
            getLetter = getchar();
        }
        for (ending = 0; ending < SIZE; ending++)
        {
            if (getLetter == '.')
                terminate = '.';
            else if (getLetter == '?')
                terminate = '?';
            else if (getLetter == '!')
                terminate = '!';
        }
        printf("Reversal of sentence: ");
        for (output = count - 1; output >= 0; output--)
        {
            holdLetter = msg[output];
            if (holdLetter == ' ')
            {
                for (second_output = len - 1; second_output >= 0;)
                    putchar(temp[second_output--]);
            }
            else
            {
                temp[len++] = holdLetter;
            }
        }
    
        printf("%c", terminate);
        printf("\n");
        system("pause");
        return 0;
    }

  5. #5
    Registered User
    Join Date
    Mar 2010
    Posts
    535
    Think about what is going into temp. After you have written "xof" into temp, you then print "fox". The space is ignored, then you're onto processing "brown".

    But temp still has "xof" in it, and you haven't reset "len" to 0 so "nworb" will be written after fox in temp and len is 8.

    You should reset len to 0 when you've finished processing a word.

    Thank you for the info on hinting to me that it won't print spaces. I believe it's because of my if(holdLetter == ' ') statement that prevents it from having spaces.
    Exactly -- if holdLetter is a space, then you don't do anything with HoldLetter in that iteration of the loop. Your if(holdLetter == ' ') logic is fine -- you do want to use that condition to trigger the outputting of the word. You could add another line of code to add a space back in -- but you could also simplify your code slightly by always writing holdLetter to temp whether it's a space or not.

  6. #6
    Registered User
    Join Date
    Mar 2010
    Posts
    535
    I guess your input string is "the quick brown fox" and you're wondering where "the" went as well.....

    Consider: your for loop goes down to element 0, which is 'T'. So 'T' is put in temp, but then the loop ends, because you only print stuff if you see a space. There's no space at the start of the string.

    You could modify your input string to have a space at the start, or change the condition under which you print a word.

  7. #7
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Welcome to the forum, Justin.

    Have you tried doing this by hand, just using paper and pencil? Imagine a very simple case, and work through it. Note the pattern (algorithm logic), you use to solve it. Put that down into small steps, and there's your program's algorithmic "backbone", right there.

    "The fox!" <===== first string

    "fox! The" <===== second string

    How would you change the first string above, into the second string?
    No code, just a description - step by step.

  8. #8
    Registered User
    Join Date
    Jul 2012
    Posts
    3

    Thank You!

    UPDATE:
    While eating a bowl of cereal, pondering how to solve this issue, I had an epiphany in which I came to the correct conclusion that in order for the if statement (holdLetter == ' ') to work properly, why not assigned the value of the first array msg[0] to ' '. By doing so the program not only recognizes that there is a space in front of the last entered problem but also recognizes when to begin a stop each loop. I've also edited the second for Loop so that the 'else if statement' takes into consideration, that if the user did not enter punctuation after a sentence, and only a line break, then it will only print out a space thus solving the mysterious character that appears if there is no punctuation. Also, I edited the the third for loop as a means in order to include the temp[len++] = holdLetter whether or not its an if statement. Ultimately the program works fantastic and I'm very happy with the results.

    A huge thank you to everyone here on the board. Thank you to whiteflags, smokeyangel, and Adak, for the the wonderful help you've provided. I especially want to commend you guys on not necessarily fixing my code but instead offering constructive criticism and feedback to problem solving. As a result of this, I was able to solve this problem from the information that was deducted from here. In other words, no on here edited my code completely and just fixed it. You guys helped me in a way that allowed me to help myself -if that makes sense haha. Thanks again guys, this board is fantastic -keep up the good work =)

    Enter Sentence: the quick brown fox!
    Reversal of sentence: fox brown quick the!
    Press any key to continue . . .
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define SIZE 100
    #define HAND 100
    
    int main()
    {
        char msg[SIZE], temp[HAND], getLetter, holdLetter, terminate;
        int count = 1, len = 0, output, second_output, ending;
    
        printf("Enter Sentence: ");
        getLetter = getchar();
        while (getLetter != '\n' && getLetter != '.' && getLetter != '?' && getLetter != '!')
        {
            msg[0] = ' ';
            msg[count] = getLetter;
            count++;
            getLetter = getchar();
        }
        for (ending = 0; ending < SIZE; ending++)
        {
            if (getLetter == '.')
                terminate = '.';
            else if (getLetter == '?')
                terminate = '?';
            else if (getLetter == '!')
                terminate = '!';
            else if (getLetter == '\n')
                terminate = ' '; 
        }
        printf("Reversal of sentence: ");
        for (output = count - 1; output >= 0; output--)
        {
            holdLetter = msg[output];
            temp[len++] = holdLetter;
            if (holdLetter == ' ')
            {
                for (second_output = len - 1; second_output >= 0;)
                {
                    putchar(temp[second_output--]);
                    len = 0;
                }
            }
        }
        printf("%c", terminate);
        printf("\n");
    
        system("pause");
        return 0;
    }

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,604
    Looks good. I notice that you have this loop:
    Code:
    for (ending = 0; ending < SIZE; ending++)
    {
        if (getLetter == '.')
            terminate = '.';
        else if (getLetter == '?')
            terminate = '?';
        else if (getLetter == '!')
            terminate = '!';
        else if (getLetter == '\n')
            terminate = ' ';
    }
    This loop does not really make sense because whether you loop once or a million times, the net effect of the loop does not change. Rather, you just need to write:
    Code:
    if (getLetter == '.')
        terminate = '.';
    else if (getLetter == '?')
        terminate = '?';
    else if (getLetter == '!')
        terminate = '!';
    else if (getLetter == '\n')
        terminate = ' ';
    Also, it is a matter of style, but instead of the above, I would prefer to write:
    Code:
    if (getLetter == '.' || getLetter == '?' || getLetter == '!')
        terminate = getLetter;
    else if (getLetter == '\n')
        terminate = ' ';
    or since you know that getLetter must be equal to one of the four:
    Code:
    terminate = (getLetter == '\n') ? ' ' : getLetter;
    Justin Page likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reversing Words and Array of Pointers
    By Striker87 in forum C Programming
    Replies: 3
    Last Post: 03-17-2011, 11:15 PM
  2. Reversing words in a string
    By rocketman03 in forum C Programming
    Replies: 4
    Last Post: 09-07-2009, 01:23 AM
  3. Reversing Letters in Words of a Sentence
    By CRSpeedy in forum C Programming
    Replies: 10
    Last Post: 03-31-2009, 06:12 PM
  4. Reversing words...noob
    By shardin in forum C Programming
    Replies: 5
    Last Post: 08-23-2007, 11:11 AM
  5. Reversing words
    By jlf029 in forum C++ Programming
    Replies: 7
    Last Post: 12-03-2005, 08:48 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21