Pages1

Reversing string using recursion: C program

Though there are several ways available in "C" to reverse string; One presented below is using recursion.
------------------------------reversestring.c---------------------------------------
#include<stdio.h>



void revStr( char a[] )
{
    if ( '\0' == a[0] )
    {
        return;
    }
    revStr(a+1);
    printf("%c",a[0]);
}

int main()
{
    revStr("Vikram");
    printf("\n");
}

Command to compiler : gcc -o rev reversestring.c
Output: When run on 64 bit Ububtu OS, compiled using gcc.
markiV
----------------------------------------------------------------

Reversing Program Using pointer and String traversing:

---------------------------------revStrPtr.c--------------------
  1 #include<stdio.h>
  2
  3 int main()
  4 {
  5   static char count;
  6   char *p = "Vikram";
  7   while( *p != '\0'  )
  8   {
  9       p++;
 10       count++;
 11   }
 12
 13   while ( count >= 0 )
 14   {
 15      printf("%c",*p);
 16      p--;
 17      count--;
 18   }
 19   printf("\n");
 20   return 0;
 21 }

Command to compiler : gcc -o revstrPtr revStrPtr.c
Output: When run on 64 bit Ububtu OS, compiled using gcc.
markiV
----------------------------------------------------------------
Explanation of potential Issues and qualifier uses:
In above program at line number 7 is replaced by "while( p != '\0'  )"
    1. Though there will be no compile time warning ,
    2. But executing program going to stuck in infinite loop.
Be careful while using such statement.

Program will work even we do not use Qualifier static, here static is use for sole purpose of initialization to value "0". But if one is willing to write both while in separate function in that case it is advisable to use static data type.



No comments:

Post a Comment