Q. Write a C program to read a string from user and display string in reverse order.
Example:
User entered string: This is a good blog
Result/output: blog good a is This
Ans.
/*c program for reverse all string*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[30];
int i,tmp;
printf("Enter any string: ");
gets(str);
for(i=0; str[i]!='\0'; i++);
for(i--; i>=0;i--)
{
if(str[i-1]==' ' || i==0)
{
for(tmp=i; str[tmp]!='\0' && str[tmp]!=' '; tmp++)
printf("%c",str[tmp]);
}
printf(" ");
}
getch();
return 0;
}
/***************Output*****************/
Related Programs:
Example:
User entered string: This is a good blog
Result/output: blog good a is This
Ans.
/*c program for reverse all string*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[30];
int i,tmp;
printf("Enter any string: ");
gets(str);
for(i=0; str[i]!='\0'; i++);
for(i--; i>=0;i--)
{
if(str[i-1]==' ' || i==0)
{
for(tmp=i; str[tmp]!='\0' && str[tmp]!=' '; tmp++)
printf("%c",str[tmp]);
}
printf(" ");
}
getch();
return 0;
}
/***************Output*****************/
Screen shot for reverse all string C program |
Related Programs:
This comment has been removed by the author.
ReplyDeleteHello Seth, I mis your past mail.
DeleteResend me your problem or u can write here for every programming lover to discuss and improve answers.
sir y u r making for(i=0; str[i]!='\0'; i++); infinite loop
ReplyDeleteIt is not infinite loop, we want to reach the end of string so i values increases till its not reach the NULL.
Deletefor example:
assume string is: India Is Awesome
for(i=0; str[i]!='\0'; i++);
to giving this loop, i's value reach the end of string i.e. NULL, and not we use string in reverse order by the following loop(according to our requirement, see above program):
for(i--; i>=0;i--)
can u explain d logic sir y u hv chosen str[i-1];
ReplyDelete@Pranav Pushp,
Deletestr[i-1] identify the blank space so we can understand that where the string one word is end and second word is start.
plz explain step by step.
ReplyDelete/*the code which works fine and the comments are also made for the better understanding of the users*/
ReplyDelete#include
#include
/*including the libraries using header files*/
int main()
{
char str[30];//declaring variables
int i,temp;
printf("enter the string to be reversed\n");
gets(str); /*takes string input*/
for(i=strlen(str); i>=0;i--) //loops from end to beginning
{
if(str[i-1]==' ' || i==0) /*condition checks for the space and 0th index*/
{
for(temp=i; str[temp]!='\0' && str[temp]!=' '; temp++) /*copies data till it reaches null or next space*/
printf("%c",str[temp]);//prints character data
}
printf(" "); //if above 2 conditions are not satisfied it'll output just a space mark
}
getchar();
return 0; //for ensuring that the program is working fine we can output any digit
}