WRITE A C PROGRAM TO REVERSE A STRING

The following C Program to reverse a string accepts a string from the user and print the reverse string. For example consider the following input from the user :

Input String : The site name is comp-psyche.com
Output String : moc.ehcysp-pmoc si eman etis ehT

Now we can reverse a string either using string function or without using string function.

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

int main()
{
 // Declaring variable str=string 
 char str[50];
 
 // Inputing string
 printf("Enter any string : ");
 gets(str);

 // Printing string and reversed string
 printf("String : %s\n",str);
 printf("Reversed string : %s",strrev(str));

 return 0;
}

WRITE A C PROGRAM TO REVERSE A STRING WITHOUT USING STRING FUNCTION



int main()
{
 // Declaring variable str=string, revstr[50]=reverse string
 char str[50], revstr[50];
 
 // Declaring variable i=to iterate loop, l=length
 int i, j,l=0;
 
 // Inputing string
 printf("Enter any string : ");
 gets(str);

 // finding length
 while(str[l]!='\0')
 l++;
 
 // Reversing string
 j=0;
 for(i=l-1;i>=0;i--)
 {
  revstr[j]=str[i];
  j++;
 }
 revstr[j]='\0';
 
 // Printing string and reversed string
 printf("String : %s\n",str);
 printf("Reversed string : %s",revstr);

}

WRITE A C PROGRAM TO REVERSE A STRING USING RECURSION


// Write a c program to reverse a string using recursion
#include<stdio.h>
void reverse (int index, char *str );

int main (void)

{

   char str[100];
   printf ("Enter any string : "); 
   gets(str);
 reverse (strlen(str) , str );
 return 0;

}

void reverse (int index, char *str )

{

  if (--index < 0 )

  {
       return ;
  }

  else
  {
        putchar ( *(str + index) ) ;  
        reverse (index, str) ;
  }

}

WRITE A C PROGRAM TO REVERSE A STRING USING POINTER

// Write a C program to reverse a string using pointer
#include<stdio.h>
int main()
{
    
    // Declaring variable str = string and revstr = to store the revere string
    char str[50];
    char revstr[50];
    
    char *strptr = str; // strptr - holds the first position address of str
    char *revptr = revstr; // revptr - holds the first position address of revstr
    int i=-1;

    // Inputting string
    printf("Enter any string : ");
    gets(str);
   
    // strptr is pointed to the last position address
    while(*strptr)
    {
        strptr++;
        i++;
    }

    // string stored in str is copied to revstr
    while(i>=0)
{
       strptr--;
       *revptr = *strptr;
       revptr++;
       --i;
    }

    *revptr='\0';
  
    printf("Reverse of string is : %s",revstr);
  
    return 0;
}


Share this

Related Posts

Previous
Next Post »

3 comments

comments
19 June 2014 at 03:31 delete

Thanks to share them. But it would be better if you write some explanation with them. :)

Reply
avatar
19 June 2014 at 03:45 delete

But it is explained through comments. I thought it was more than enough.

Reply
avatar