I am attempting to reverse a string for a homework assignment and then reverse each word in the string. The trick is we are suppose to code it without using functions. Like "I like cats" should be 1st "stac ekil I" and then "cats like I". Here is what I have so far:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[40], temp, start, last, count;
    int len, l, r, x;
    printf("Please input a sentence (under 40 characters) followed by a period.\n");
    gets(str);
    len = strlen(str);


    l = 0;
    r = len - 1;

    while (l < r) // reverses the whole string
            {
                temp=str[l];
                str[l++] = str[r];
                str[r--] = temp;
            }

    /*for (x = 0; x <=len - 1; x++)
        printf("%c", str[x]);*/

    count = 0;
    start = 0;
    for (x = 0; x <= len -1; x++) // reverses each word
    {
        ++count;
        if (str[x] == ' ')
            last = x - 1;
            start = last - count + 1;
        while (start < last)
            {
                char temp;
                temp=str[start];
                str[start++] = str[last];
                str[last--] = temp;
            }
        count=0;
    }
    for (x = 0; x <=len - 1; x++)
        printf("%c", str[x]);





return 0;
}

Recommended Answers

All 12 Replies

Go from back to front, and use a temporary buffer to hold the data until done. IE,

for (int i = strlen(input) - 1, j = 0; i <= 0; i--, j++)
{
    temp[j] = input[i];
}
temp[j] = 0;
output = temp;

Just FYI, this won't work, but it is close. The changes are your exercise! :-)

This assignment contains easy to identify subtasks which can be expressed in their own functions. Following this idea I would suggest something like the following:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>

// The maximum length of a string.
#define STRING_MAX (40)

// Function declarations/prototypes.
void reverse_substring (char str[], int start, int end);
void reverse_words     (char str[], const int length);

// Reverse the substring within 'str' starting at index 'start' and ending at index 'end'.
void reverse_substring (char str[], int start, int end)
{
    // Little check to ensure correct parameters.
    // Not checking if end < strlen(str) so str doesn't have to be NULL-terminated.
    assert (str != NULL);

    char temp = 0;

    while (start < end)
    {
        // Store the character that's on the left side.
        temp = str[start];

        // Overwrite the character that's on the left side with the one that's on
        // the right side. And move the left index one to the right afterwards.
        str[start++] = str[end];

        // Overwrite the character that's on the right side with
        // the backup of the one that used to be left.
        str[end--] = temp;
    }
}

// Reverse the contents of words in a given string.
void reverse_words (char str[], const int length)
{
    // Not checking for string length so it doesn't have to be NULL-terminated.
    assert (str != NULL);

    int i           = 0,    // Counter to iterate over the string.
        start_found = 0,    // Flag that shows if we're looking for the beginning or the end of a word.
        word_start  = 0;    // Index of the first character of a word.

    // Go over the entire string.
    for (i = 0; i < length; i++)
    {
        // We're looking for the start of a word.
        if (!start_found && !isspace(str[i]))
        {
            // We've found the start of a word! Store it's index.
            word_start = i;

            // Now start looking for the end.
            start_found = 1;
        }

        // We've already found the starting point but we're looking for the end.
        // The end is the character before the first whitespace, so we've found it!
        else if (start_found && isspace(str[i]))
        {
            // Reverse the substring.
            reverse_substring(str, word_start, i - 1);

            // Reset our flag for the next word.
            start_found = 0;
        }
    }

    // The final word is likely not terminated by a whitespace.
    // Check if we were in the process of finding the end of a word and reverse it.
    if (start_found)
    {
        reverse_substring(str, word_start, length - 1);
    }
}


int main(void)
{
    char str[STRING_MAX + 1];   // Used to store the string.
    int  len = STRING_MAX;      // Length of the entered string.

    // gets() is deprecated. Use fgets() instead.
    printf("Please input a sentence consisting of at most %d characters.\n", STRING_MAX);

    if (fgets(str, len + 1, stdin) != NULL)
    {
        // In case more characters were supplied than our buffer can hold. Clear the remaining ones.
        fflush(stdin);

        // Store the length of supplied string.
        len = strlen(str);

        // fgets() stores the newline too, remove it if it's present.
        if (len > 0 && str[len - 1] == '\n')
        {
            str[len - 1] = '\0';
            len--;
        }

        // Reverse the whole string.
        reverse_substring(str, 0, len - 1);

        // The string is now reversed. A for-loop is not needed as gets supplies a null-terminated string.
        printf("Reversed string: %s\n", str);

        // Next, reverse the contents of every word.
        reverse_words(str, len);

        // The string is now reversed. A for-loop is not needed as gets supplies a null-terminated string.
        printf("Reversed string with reversed words: %s\n", str);
    }
    else
    {
        printf("Error on reading input.\n");
    }

    return 0;
}

I've commented the code pretty thoroughly so I think it's self-explanitory but if anything is unclear feel free to ask. Some things could have been done more compact but I prefer readability in this case, especially when trying to help someone over forums.

And in case someone downvotes me again for trying to help: I did it out of boredom, and I will do it again if the conditions are the same..

-edit-
When you stated 'no functions' I assumed library functions by the way, it would be a silly demand otherwise. I also assumed that usage of functions that do a substantial amount of work are prohibited but functions like "isspace" are fine to be used. If not you could replace them with your own one I suppose.

commented: Yes you deserve this +0
commented: some more well deserved neg rep from me... -2
Member Avatar for iamthwee

^^ Doing someone's homework out of boredom serves absolutely no purpose.

The OP gets a freebie answer and passes his course. When quizzed in the real world what do you think is going to happen? He needs to learn, you have taken away what others might have otherwise achieved through careful wording and nudging in the right direction.

Although this approach is almost twice as time consuming it's ALWAYS better for the OP than getting a freebie answer.

Give yourself a clap for being a class A idiot. And if you're bored why not go add to the hundreds of thousands of open source projects out there.

commented: Terrible logic. +0

^^ "The OP gets a freebie answer and passes his course". Sure he gets an answer. What he does with it is his choice though. If he is indeed one of the people that hands this one in without trying to understand it himself, do you really think your supposedly brilliant 'nudges in the right direction' would have learned him anything? It wouldn't. He would do the absolute bare minimum and not really attempt to learn. Sure, he might have to look some things up and will likely paste some snippets but if he's truly looking just to get rid of the assignment it's all in vain anyway.

I assume that people who ask things actually have the intention to understand it. An example code will serve as a good point to start in my opinion and could serve as a base of other question.

Oh and please refrain from calling people you do not know 'class A idiots', you wouldn't want to be seen as one yourself I presume. And I am already contributing to open-source projects; One activity doesn't rule out the other.

Have a good day, bright light.

commented: I am Iamthwee and I disagree with this post. -3
Member Avatar for iamthwee

Sure he gets an answer. What he does with it is his choice though.

Really, if that was the case why don't we all just post up the answers to everyones' homework? In fact, why don't teachers just bypass giving homework altogether and give out questions with model solutions?

If you really expect someone to buy your BS at least give plausible reasoning, not some BS you just pulled out of your a##.

do you really think your supposedly brilliant 'nudges in the right direction' would have learned him anything?

Again, you clearly miss the purpose of setting homework. To you, it's more instructional to just hand out solutions. Hands up anyone who agrees with this? Come on now, don't be shy.

Oh and please refrain from calling people you do not know 'class A idiots'

I do apologise, what's even worse - is that even now you don't see the error of ways and still continue to justify why its a good idea to hand out full solutions to homework questions. I've upgraded you to a class A+ idiot. Congratulations.

. And I am already contributing to open-source projects; One activity doesn't rule out the other.

Never said it did. But contributing to one helps whereas the other 'i.e doing someone's homework' clearly doesn't.

Have a good day, bright light.

Thanks! You too... and Ima down rep you again just incase my point has been missed. You seem to have a great knack of reading but not really taking it in.

commented: Hahaha, I downvoted this because it's contents are simply dumb but it gave me a laugh while reading. Thanks! +0

i dono y ur complicating too much just try this

#include <stdio.h>
#include <stdlib.h>

void main()
{
    char a[50];
    int n,i;
    printf("enter the string  : ");
    gets(a);
    n=strlen(a);
    printf("%d",n);
for(i=n;i>=0;i--)
    {
        printf("%c",a[i]);
    }



}

i dono y ur complicating too much just try this

The question wants you to reverse the entire string then each word within the string.

Example,

Our string:
"The sky is blue"

Reverse the entire string:
"eulb si yks ehT"

Reverse each word in the string:
"blue is sky The"

As a result, the words are reversed, not the letters.

Really, if that was the case why don't we all just post up the answers to everyones' homework?

You tell me. Just because 'everyone' (which is not even true, but okay) does something, it doesn't mean it's logical or the best thing to do. (A controversial example would be religion if you'd ask me)

In fact, why don't teachers just bypass giving homework altogether and give out questions with model solutions?

If you've ever gone to school you'd know that partially you do get provided examples of good practices. Generally these are subsets of bigger problems that have to be solved later but they can sometimes be a larger example too as these introduce additional complications.

Your statement is very short-sighted as it implies teacher ONLY give homework, which is ofcourse not true.

If you really expect someone to buy your BS at least give plausible reasoning, not some BS you just pulled out of your a##.

Right back at you. Everything you said so far was completely biased.

Again, you clearly miss the purpose of setting homework. To you, it's more instructional to just hand out solutions. Hands up anyone who agrees with this? Come on now, don't be shy.

Again, you want to try to get people behind you to back you up. Should I interpret this as an obvious sign of you being insecure about your own stance? Provided that I seem to have provoked you I guess I will.

Regarding your 'point' directly, I do think YOU don't understand the purpose of homework. More precisely, you don't understand the role of these forums.

Just to make it clear for you, taking into account that you might be unschooled going by one of the previous comments, this forum is to help people with their problems. Teachers and schools have the task to test people on their knowledge and reward them accordingly. If it wasn't clear to you, there's a difference there. It's not our task to test the knowledge level of the people that post their question here. THAT is the task of their teachers and schools. I cannot phrase this more clearly than I already did, I hope you understand it. I can try drawing pictures for you next time if this helps.

I do apologise, what's even worse - is that even now you don't see the error of ways and still continue to justify why its a good idea to hand out full solutions to homework questions. I've upgraded you to a class A+ idiot. Congratulations.

Just because you don't agree with it doesn't mean it's an error obviously. I can say EXACTLY the same thing about your statements which appear increasingly dumb to me. Regarding my new rank: thanks I guess, although I'm afraid the judgement passed on by someone as incapable and short-sighted (not to mention short-fused) as yourself can hardly get to me. Considering your passion of assigning ranks to people, I'll give you one as well! How does "clown" sound to you? It doesn't quite reflect your "my way is the only way!!" attitude but you do have this laughing effect on me, although the latter is likely unintentional.

Never said it did. But contributing to one helps whereas the other 'i.e doing someone's homework' clearly doesn't.

You're not in the position to judge whether or not my post helped or not. This is up to the person posing the question. I like how you add "clearly" again by the way. Your response are clearly very right and not to forget, the ONLY right awnser, ofcourse! So I clearly shouldn't have to correct you on some things, but I'm sure you did that intentionally just to make sure I'd reply again. Don't worry, you're my favorite clown.

Thanks! You too... and Ima down rep you again just incase my point has been missed. You seem to have a great knack of reading but not really taking it in.

Okay, 'ima' down-rep you again as well. Although I must say I considered upvoting it as the sheer idiocy of it gave me a good laugh. I guess I should take the knack of reading as a compliment. Here's something to read for you: Did you know there's a possibility people don't 'take it in' because they simply don't agree with you? I promise you this is actually possible!

Well I'm off again for today. Again thanks for the chuckle and it's probably the last time I spend on it. I hope we meet in other threads again. You seem to get upset easily though so I hope this doesn't cause problems for you, haha.

Well, see you later clown!

Yours truly,

'class A+ idiot'®

@rithish...you print the string in reverse order. that not the question. you have to store it too.

@straylight...your solution to first part is:

  1. calculate length of string
  2. find half of it.(take care of odd and even length)
  3. run a loop from starting to length/2 and start swapping the first and last character.

for 2nd part
1. you have to use the above generated string for this.
2. do the above steps for each word (i mean till every space in a string).
you get the desired answer. check it yourself

Time for a Moderator to weigh in. I'm raising my hand.

Gonbe: Do NOT give full working answers to questions. Guide them to writing their own solutions.

Gonbe: If you've ever gone to school you'd know that partially you do get provided examples of good practices. Generally these are subsets of bigger problems that have to be solved later but they can sometimes be a larger example too as these introduce additional complications.

You are proving our point. Notice your own wording: "examples of good practices" and "Generally these are subsets of bigger problems". How is your code an example or a subset. Isn't it full, working, hand-in code? Even by your definition it's wrong.

Gonbe: Regarding your 'point' directly, I do think YOU don't understand the purpose of homework. More precisely, you don't understand the role of these forums.

After 19 posts you know more about these forums than the rest of us? Hmmm, sounds like a bit of self-deluded arrogance to me. What makes you such an expert suddenly?

Member Avatar for iamthwee

If you've ever gone to school you'd know that partially you do get provided examples of good practices.

Partially, so tell me again why you posted up the whole thing? Oh yeah you're full of contradictions. Much like:-

And in case someone downvotes me again for trying to help: I did it out of boredom, and I will do it again if the conditions are the same..

You seem like you KNEW you were going to get downvoted for this. Great, all you had to do was NOT post it. What other circular arguments do you have with yourself...

"Gee I know my hand is going to get burned if I put my hand in the fire but I'll just do it anyway as I'm bored."

LOL, but seriously you're right. In fact, I'm going to just post up entire solutions for kids when they ask homework questions. I'm going to write a letter to all educational bodies and tell them of your universal teaching style where homework shouldn't be about thinking for yourself but just copying complete solutions from online forums.

So dear valuable daniweb members, you're clearly wasting your time. Next time just post the entire answer when a student asks a homework question. Wholly crap I'm such a clown.

Hurray!

ooh good task ill surely try this

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.