Written by Sai Sandeep Thota on January 3, 2013 in C > Programming

Reverse a String using C Programming

GET ALERTS:

Get our Latest updates delivered to your mailbox!

The below program describes how to reverse a given input String. For example: input string is ‘sandeep‘ reversed string must be ‘peednas‘.

Reverse a String

    1. First read the input given by the user.
    2. Next put a while condition that increments Length and i value until it encounters a NULL value in the given string.
    3. Next copy the contents of given input string into a new variable, by using a for loop.
#include<stdio.h>
#include<conio.h>
void main()
{
      char a[50],b[50];
      int length=0,i=0, j=0;
      printf("Enter an input String: ");
      gets(a);
      while(a[i]!='\0')
      {
                       length++;
                       i++;
      }
      for(i=length-1;i>=0;i--)
      {
                       b[j] = a[i];

                       j++;

      }
      b[j++] = '\0';
      printf("Reversed String is: ");
      puts(b);
      getch();
}

Practical Example:
Input String: sandeep
1. Read the string into variable ‘a’.
2. Length will be incremented, i will be incremented. [Length = 6, i = 6].
3. So for condition will look something like this: for(i=6-1;i>=0;i–)
4. So In a[i], ‘i’ will contain 5 during its first iteration, 4 during second iteration and goes on until 0.
5. In b[j], ‘j’ value starts from 0 and as we are copying b[j]=a[i], The string is copied in reverse order into b array.
6. Output
String-Reverse

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: