Reverse a string without using library functions

Lets see how we can reverse a string without using library functions.

Code

#include<stdio.h>

int main()
{
    char str[20],temp;
    int i,j;

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

    j = 0;

    while (str[j] != '\0')                       //calc length of str
        j++;

    j--;                                         //positioned on last character

    for(i=0;i<j;i++,j--)
    {
            temp = str[i];                       //swap str[i] and str[j]
            str[i] = str[j];
            str[j] = temp;
    }

    printf("\nReverse string = %s",str);

    return 0;
}

O/P




Code Tracing

i           j
p r o g r a m             Swap p and m

i           j
m r o g r a p             Inc i,dec j

  i       j
m r o g r a p             Swap r and a

  i       j
m a o g r r p             Inc i,dec j

    i   j
m a o g r r p             Swap o and r

    i   j
m a r g o r p             Inc i,dec j 

      i,j
m a r  g   o r p          Stop when i==j

Lets see how we can reverse a string using pointers.

Code

#include<stdio.h>

int main()
{
    char str[20],temp;
    char *i,*j;

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

    j = str;

    while (*j != '\0')                        
        j++;

    j--;                                     //j points to last character

    for(i=str;*i!=*j;i++,j--)
    {
            temp = *i;                       //swap *i and *j
            *i = *j;
            *j = temp;
    }

    printf("\nReverse string = %s",str);

    return 0;
}

No comments:

Post a Comment