473,835 Members | 2,263 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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=NUL L,*temp,*last=N ULL;

printf("Enter the sentence: ");
str=fgets(msg,s izeof(msg),stdi n);

while(str[i]!='\0')
{
if((str[i]==' ')||(str[i]=='\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[i];
j++;
}
i++;
}

temp=front;
while(temp)
{
length++;
printf("%s ",temp->info);
temp=temp->next;
}
printf("\nLengt h 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.

Nov 14 '05 #1
8 7611
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("printin g '%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");
}

Nov 14 '05 #2

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

Nov 14 '05 #3
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=NUL L,*temp,*last=N ULL;

printf("Enter the sentence: ");
str=fgets(msg,s izeof(msg),stdi n);
Check the return value of fgets() -- it may be NULL!

while(str[i]!='\0')
{
If you use a pointer, you might "really" do it.
I.e.
for (str=msg; *str != '\0'; str++)
and all occurrences of str[i] 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[i]==' ')||(str[i]=='\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[i] = 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[i];
j++;
}
i++;
}

temp=front;
while(temp)
{
length++;
printf("%s ",temp->info);
temp=temp->next;
}
printf("\nLengt h 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.
Nov 14 '05 #4
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("printin g '%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.
Nov 14 '05 #5
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

Nov 14 '05 #6
"vijay" <Ta***********@ yahoo.com> 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.
Nov 14 '05 #7
<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[i] = 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.

Nov 14 '05 #8
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

Nov 14 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
13748
by: Erik Andersson | last post by:
Hi! I need to read a file (line-by-line) in reverse order, without reading the whole file into memory first. Is there an easy way of doing this? As in, is there a PHP function I could use? The solution has to be platform independent, so "popen("tac $filename")... wouldn't work.
3
2793
by: James Lee | last post by:
I am doing a simple query like col1, col2, date, col4 from table1. All four colums are of type blob. For date column, I store a string like this: Fri Feb 13 11:01:24 2004 I store records as they come in so the oldest record is at the top of the table. When I select and display, I want to display them in reverse order (newest record at the top) but I can't sort on date with strings like that.
20
33088
by: sahukar praveen | last post by:
Hello, I have a question. I try to print a ascii file in reverse order( bottom-top). Here is the logic. 1. Go to the botton of the file fseek(). move one character back to avoid the EOF. 2. From here read a character, print it, move the file pointer (FILE*) to 2 steps back (using fseek(fp, -2, SEEK_CUR)) to read the previous character. This seems to be ok if the file has a single line (i.e. no new line character). The above logic...
10
5402
by: aatish19 | last post by:
1: Write a program that asks the user to input an integer value and print it in a reverse order Sample Output Enter any number 65564 Reverse of 65564 is 46556 2: Write a program that takes a string as an input and print it in reverse order.(don't use bulit-in/library function). Sample Output Enter any string: i m Kashif
3
4076
by: thrill5 | last post by:
I have an xml document such as: <device> <element>first</element> <element>second</element> </device> I am using this as the source for an xslt transform that goes like <xsl:for-each select="/device/element> This is the <xsl:value-of select="."/> element.
2
8565
by: srp8982 | last post by:
hello, I need help (code) on following program ,its in c... 1)allow user to write file name in command line, read the file... 2) count characters, spaces and no. of lines in file given... 3)read upto first 10 lines, and print them in reverse order thanking you in advance
6
18113
by: raghuveer | last post by:
i want to print my linked list in the reverse order ie..last item first and first item last..this is what i have so far struct linked_list { int number; struct linked_list *next; }; typedef linked_list node;
6
6898
by: bitong | last post by:
The problem is input a number then the output should be in reverse order.. I already made a code but only good for 9 - digit only...What I want to do is to hold infinite digit, in other words don't have a limit on how many digit that I want to input.. for (x = y;x>0;x=x/10){ z = x % 10; cout<<z; } * code good for 9 - digit only, if I input 10 digit its...
1
2363
by: Charles Smith | last post by:
Using vba in access to print multi page reports. I would like to have them print in reverse order.
0
9803
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10523
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10560
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10233
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9345
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5636
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4434
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3993
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3088
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.