to print in the reverse order, ("Hello World" -> "World Hello")

Discussion in 'C Programming' started by vijay, Apr 24, 2005.

  1. vijay

    vijay Guest

    Hello,

    As the subject suggests, I need to print the string in the reverse
    order. I made the following program:

    # include<stdio.h>

    struct llnode
    {
    char *info;
    struct llnode *next;
    };

    typedef struct llnode NODE;

    int main()
    {
    char msg[50],word[10],*str;
    int i=0,length=0,j=0;
    NODE *ptr,*front=NULL,*temp,*last=NULL;

    printf("Enter the sentence: ");
    str=fgets(msg,sizeof(msg),stdin);

    while(str!='\0')
    {
    if((str==' ')||(str=='\n'))
    {
    word[j]='\0';
    j=0;
    ptr=(NODE *)malloc(sizeof(NODE));
    ptr->info=word;
    ptr->next=NULL;

    if(front==NULL)
    {
    front=ptr; // only change the value of
    front here
    }
    else
    {
    temp=front;
    while((temp->next)!=NULL)
    {
    temp=temp->next;
    }
    temp->next=ptr;
    }
    printf("\n##%s\n",front->info); // prints the
    words and not //
    the first word
    }
    else
    {
    word[j]=str;
    j++;
    }
    i++;
    }

    temp=front;
    while(temp)
    {
    length++;
    printf("%s ",temp->info);
    temp=temp->next;
    }
    printf("\nLength of Linked List(or, number of words):
    %d\n",length);

    i=0;
    printf("\n************************\n");

    while(i<length)
    {
    temp=front;
    while(temp->next!=last)
    {
    temp=temp->next;
    }
    last=temp;
    printf("%s ",temp->info);
    i++;
    }

    return 0;
    }

    Here, front is a poiter to the first node. But when I print
    front->info, I get different words, I mean "Hello" once and "World",
    the second time. I nowhere change the value of fromt except in the
    first if statement.

    The length of the linked list is printed correctly. And sorry for
    pasting such a big code in the post itself, I had no other option.

    The output is:

    [vijay@vijay ds]$ ./a.out
    Enter the sentence: Hello World

    ##Hello

    ##World
    World World
    Length of Linked List(or, number of words): 2

    ************************
    World World [vijay@vijay ds]$


    regards,
    vijay.
    vijay, Apr 24, 2005
    #1
    1. Advertising

  2. vijay wrote:
    > Hello,
    >
    > As the subject suggests, I need to print the string in the reverse
    > order.


    I came up with this:

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

    void
    print_it(const char *str)
    {
    char *ptr, *lbuf;

    if (str == NULL || strlen(str) == 0) return;
    lbuf = strdup(str);

    printf("printing '%s' in reverse order:\n", str);

    while ((ptr = strrchr(lbuf, ' ')) != NULL) {
    printf("%s ", ptr + 1);
    *ptr = '\0';
    }
    printf("%s\n", lbuf);
    free(lbuf);
    }

    int
    main(void)
    {
    print_it(NULL);
    print_it("");
    print_it("world");
    print_it("hello world");
    print_it("i am lucky i can program c");
    }
    Peteris Krumins, Apr 24, 2005
    #2
    1. Advertising

  3. Peteris Krumins wrote:
    > vijay wrote:
    > > Hello,
    > >
    > > As the subject suggests, I need to print the string in the reverse
    > > order.

    >
    > I came up with this:
    >


    Forgot to #include <stdlib.h>
    and return an int from main()


    P.Krumins
    Peteris Krumins, Apr 24, 2005
    #3
  4. vijay

    Michael Mair Guest

    vijay wrote:
    > Hello,
    >
    > As the subject suggests, I need to print the string in the reverse
    > order. I made the following program:


    Please do not use // comments in code posted to usenet as
    linebreaks can introduce unintentional bugs which are not
    there in your version of the code.
    Apart from that, less indentation helps keeping the lines
    at a sensible length.

    > # include<stdio.h>
    >
    > struct llnode
    > {
    > char *info;
    > struct llnode *next;
    > };


    (*)
    Note: info just _points_ to something but does provide
    no storage.

    >
    > typedef struct llnode NODE;
    >
    > int main()
    > {
    > char msg[50],word[10],*str;
    > int i=0,length=0,j=0;
    > NODE *ptr,*front=NULL,*temp,*last=NULL;
    >
    > printf("Enter the sentence: ");
    > str=fgets(msg,sizeof(msg),stdin);


    Check the return value of fgets() -- it may be NULL!

    >
    > while(str!='\0')
    > {


    If you use a pointer, you might "really" do it.
    I.e.
    for (str=msg; *str != '\0'; str++)
    and all occurrences of str replaced by *str.
    Otherwise, I suggest a i = 0 directly before the
    loop, so later changes between the initialization
    and the loop start do not introduce errors there.

    > if((str==' ')||(str=='\n'))
    > {
    > word[j]='\0';
    > j=0;
    > ptr=(NODE *)malloc(sizeof(NODE));


    Check the return value of malloc() -- it returns NULL if
    no memory could be allocated. You then should do some error
    handling and maybe die gracefully.
    The cast is completely unnecessary and potentially dangerous.

    > ptr->info=word;
    > ptr->next=NULL;


    Now, ptr->info points to &word[0].
    For every NODE you create, ptr->info contains the
    _same_ address. Thus, you get only the content of
    word[]. What you want is to make str = 0 and point
    ptr->info at &str[i-j].

    > if(front==NULL)
    > {
    > front=ptr; // only change the value of
    > front here
    > }
    > else
    > {
    > temp=front;
    > while((temp->next)!=NULL)
    > {
    > temp=temp->next;
    > }
    > temp->next=ptr;
    > }


    This is very inefficient.
    Create an empty "front" NODE and keep a "curr" NODE* to point at the
    last node in the list. Then, you allocate
    curr->next;
    If this works, you set curr = curr->next; curr->next = NULL;
    curr->info = ....

    Alternatively, you could _prepend_ the node to the list.
    I.e. you allocate and initialise ptr, and then make ptr->next = first;
    first = ptr. Then, your list is already sorted the way you want.

    > printf("\n##%s\n",front->info); // prints the
    > words and not //
    > the first word
    > }
    > else
    > {
    > word[j]=str;
    > j++;
    > }
    > i++;
    > }
    >
    > temp=front;
    > while(temp)
    > {
    > length++;
    > printf("%s ",temp->info);
    > temp=temp->next;
    > }
    > printf("\nLength of Linked List(or, number of words):
    > %d\n",length);
    >
    > i=0;
    > printf("\n************************\n");
    >
    > while(i<length)
    > {
    > temp=front;
    > while(temp->next!=last)
    > {
    > temp=temp->next;
    > }
    > last=temp;
    > printf("%s ",temp->info);
    > i++;
    > }
    >
    > return 0;
    > }
    >
    > Here, front is a poiter to the first node. But when I print
    > front->info, I get different words, I mean "Hello" once and "World",
    > the second time. I nowhere change the value of fromt except in the
    > first if statement.
    >
    > The length of the linked list is printed correctly. And sorry for
    > pasting such a big code in the post itself, I had no other option.
    >
    > The output is:
    >
    > [vijay@vijay ds]$ ./a.out
    > Enter the sentence: Hello World
    >
    > ##Hello
    >
    > ##World
    > World World
    > Length of Linked List(or, number of words): 2
    >
    > ************************
    > World World [vijay@vijay ds]$
    >
    >
    > regards,
    > vijay.
    >



    --
    E-Mail: Mine is an /at/ gmx /dot/ de address.
    Michael Mair, Apr 24, 2005
    #4
  5. vijay

    Michael Mair Guest

    Peteris Krumins wrote:
    > vijay wrote:
    >
    >>Hello,
    >>
    >>As the subject suggests, I need to print the string in the reverse
    >>order.

    >
    >
    > I came up with this:
    >
    > #include <stdio.h>
    > #include <string.h>
    >
    > void
    > print_it(const char *str)
    > {
    > char *ptr, *lbuf;
    >
    > if (str == NULL || strlen(str) == 0) return;
    > lbuf = strdup(str);


    strdup() is not a standard library function, so you should
    grace us with a prototype and description or do an example
    implementation.

    >
    > printf("printing '%s' in reverse order:\n", str);
    >
    > while ((ptr = strrchr(lbuf, ' ')) != NULL) {
    > printf("%s ", ptr + 1);
    > *ptr = '\0';
    > }
    > printf("%s\n", lbuf);
    > free(lbuf);
    > }
    >
    > int
    > main(void)
    > {
    > print_it(NULL);
    > print_it("");
    > print_it("world");
    > print_it("hello world");
    > print_it("i am lucky i can program c");
    > }
    >



    --
    E-Mail: Mine is an /at/ gmx /dot/ de address.
    Michael Mair, Apr 24, 2005
    #5
  6. Michael Mair wrote:
    >
    > strdup() is not a standard library function, so you should
    > grace us with a prototype and description or do an example
    > implementation.
    >


    Excuse me, I forgot that strdupn was not a stdlib. function.

    My implementation of strdup is as follows:

    #include <string.h>
    #include <stdlib.h>

    char
    *strdup(const char *s)
    {
    int size;
    char *newthing;

    if (s == NULL) return NULL;
    size = strlen(s) + 1;
    if ((newthing = malloc(size)) == NULL) return NULL;
    return memcpy(newthing, s, size);
    }


    P.Krumins
    Peteris Krumins, Apr 24, 2005
    #6
  7. vijay

    SM Ryan Guest

    "vijay" <> wrote:
    # Hello,
    #
    # As the subject suggests, I need to print the string in the reverse
    # order. I made the following program:

    If that's all you want, you can write a function say f

    f(string) =
    if string is not empty,
    let w = last entity of string
    let p = first part of string (may be empty)
    f(p)
    print w

    For example to reverse characters

    ...
    void f(char *s,int n) {
    if (n>0) {
    char w = s[n-1];
    f(s,n-1);
    fputc(w,stdout);
    }
    }
    ...
    f(string,strlen(string));
    ...

    --
    SM Ryan http://www.rawbw.com/~wyrmwif/
    We found a loophole; they can't keep us out anymore.
    SM Ryan, Apr 24, 2005
    #7
  8. vijay

    vijay Guest

    <snip>

    > > ptr->info=word;
    > > ptr->next=NULL;

    >
    > Now, ptr->info points to &word[0].
    > For every NODE you create, ptr->info contains the
    > _same_ address. Thus, you get only the content of
    > word[]. What you want is to make str = 0 and point
    > ptr->info at &str[i-j].


    This was the problem. It always pointed to the last word, and therefore
    "front" always printed the last word.

    >
    > > if(front==NULL)
    > > {
    > > front=ptr; // only change the

    value of
    > > front here
    > > }
    > > else
    > > {
    > > temp=front;
    > > while((temp->next)!=NULL)
    > > {
    > > temp=temp->next;
    > > }
    > > temp->next=ptr;
    > > }

    >
    > This is very inefficient.
    > Create an empty "front" NODE and keep a "curr" NODE* to point at the
    > last node in the list. Then, you allocate
    > curr->next;
    > If this works, you set curr = curr->next; curr->next = NULL;
    > curr->info = ....


    Is this how linked lists are created? "front" poiting to the empty node
    which in turns points to the first node and "curr" pointing to the
    first node.

    >
    > Alternatively, you could _prepend_ the node to the list.
    > I.e. you allocate and initialise ptr, and then make ptr->next =

    first;
    > first = ptr. Then, your list is already sorted the way you want.


    Yes, even this is a good work-around.

    Thanks to Peteris too. Your solution was very simple. This is where I
    guess is the diference between a good programmer and a not-so-good
    programmer, the design of the solution. I thought of making it with the
    help of linked list, pinch of complexity in itself.

    regards,
    vijay.
    vijay, Apr 25, 2005
    #8
  9. vijay

    Neil Guest

    vijay wrote:
    Hello,

    As the subject suggests, I need to print the string in the reverse
    order. I made the following program:

    Well, this is something that you should work on, because this type of
    programming is found in alot of C books. I 'm surprised your here with
    this post, generally this excercise is suppose to train you how to use
    the debugger with arrays and loops and so on. It also makes you think a
    little on the problem, and to be creative with programming in C or any
    language for that matter, but here is what the code looks like, but I
    could of made a syntax error, so don't take my word for it

    there are many answers to this........:)

    #include <stdlib>

    #define MAX 80 /* the constant which defines the array(limit).*/

    int main(void)
    {
    char ch, letters[MAX];
    int count = 0;

    printf("Enter a sentence and hit Enter -> ");
    while ((ch = getchar()) != '\n'))/* Searching for the end of chars*/
    {
    letters[count++] = ch;
    }

    letters[count] = '\0'; /* insert NULL last in the string array*/

    for (--count, count >= 0, --count) /* counts back each letter*/
    {
    putchar(letters[count]); /* at the last count in the array */

    } /* then prints each one*/

    }
    Simply enough, you could of used the strlen() function to count the
    characters if you want to, but this is by far much easier. I have seen
    it done with recursion, that makes the code very small, but hard to
    understand.

    OK
    -neil
    Neil, Apr 26, 2005
    #9
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Assignment: Print reverse order

    , Apr 12, 2006, in forum: C Programming
    Replies:
    10
    Views:
    538
    Wolfgang Riedel
    Apr 13, 2006
  2. Roy
    Replies:
    6
    Views:
    580
    Roedy Green
    Jan 7, 2008
  3. Gestorm

    How can I print a red "Hello world"

    Gestorm, Jun 16, 2008, in forum: C Programming
    Replies:
    3
    Views:
    250
    Gestorm
    Jun 16, 2008
  4. Henrik Bechmann

    Invalid syntax with print "Hello World"

    Henrik Bechmann, Mar 12, 2009, in forum: Python
    Replies:
    10
    Views:
    31,260
    bob gailer
    Nov 14, 2013
  5. Larry
    Replies:
    27
    Views:
    413
    Michele Dondi
    Jan 25, 2005
Loading...

Share This Page