7.01.2012

Reverse all string

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*****************/


Reverse all string C program output
Screen shot for reverse all string C program



Related Programs:

  1. Reverse all words but not string
  2. Reverse each first character of word & add extra word
  3. Change case of string(Toggle/Title Case)
  4. Display string vertically
  5. Search sub string from main string
  6. Search sub string individual from main string
  7. Position and repetition of character in string

8 comments:

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Hello Seth, I mis your past mail.
      Resend me your problem or u can write here for every programming lover to discuss and improve answers.

      Delete
  2. sir y u r making for(i=0; str[i]!='\0'; i++); infinite loop

    ReplyDelete
    Replies
    1. It is not infinite loop, we want to reach the end of string so i values increases till its not reach the NULL.
      for 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--)

      Delete
  3. can u explain d logic sir y u hv chosen str[i-1];

    ReplyDelete
    Replies
    1. @Pranav Pushp,

      str[i-1] identify the blank space so we can understand that where the string one word is end and second word is start.

      Delete
  4. /*the code which works fine and the comments are also made for the better understanding of the users*/


    #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
    }

    ReplyDelete