Saturday, 9 February 2013

C program for Reversing a string and palindrome checking with explanation

Step 1:

Open the IDE and type the coding given here.

Step 2:

CODING:

#include<stdio.h>
#include<string.h>
main()
{
    char str[80], rev[80];
    int i,j,len;
    printf("Reversing the string and checking for palindrome\n\n");
    printf("Enter string\n");
    gets(str);
    len=strlen(str);
    for(i=len-1,j=0;i>=0;i--,j++)
    rev[j]=str[i];
    rev[j]='\0';
    printf("Entered string is ");
    printf(str);
    printf("\n\n");
    printf("reversed string is ");
    printf(rev);
    printf("\n\n");
    if(strcmp(str, rev)==0)
    printf("\n\n%s is a palindrome", str);
    else
    printf("\n\n%s is not a palindrome", str);
    getch();
}

OUTPUT:


EXPLANATION:
str, revi,j,len are declared.
strlen() calculates the length of a string.

i  0  1  2  3
   r  o  s   e 
for loop reverses the string as:
j  0  1  2  3
   e  s  o  r
strcmp compares the two strings.