About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Wednesday, September 4, 2013

C Program to Reverse String Without Using Library Function

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

void main()
{
 char str[100],temp;
 int i,j=0;

 printf("\nEnter the string :");
 gets(str);

 i=0;
 j=strlen(str)-1;

 while(i<j)
     {
     temp=str[i];
     str[i]=str[j];
     str[j]=temp;
     i++;
     j--;
     }

 printf("\nReverse string is :%s",str);
 return(0);
}

Output :

Enter the string  : Pritesh
Reverse string is : hsetirP

Explanation Of Program :

Firstly find the length of the string using library function strlen().
j = strlen(str)-1;
Suppose we accepted String “Pritesh” then -
j = strlen(str)-1;
  = strlen("Pritesh") - 1
  = 7 - 1
  = 6
As we know String is charracter array and Character array have character range between 0 to length-1. Thus we have position of last character in variable ‘j’.Current Values of ‘i’ and ‘j’ are -
i = 0;
j = 6;
‘i’ positioned on first character and ‘j’ positioned on last character. Now we are swapping characters at position ‘i’ and ‘j’. After interchanging characters we are incrementing value of ‘i’ and decrementing value of ‘j’.
while(i<j)
     {
     temp   = str[i];
     str[i] = str[j];
     str[j] = temp;
     i++;
     j--;
     }

No comments: