facebook like button

10 April, 2011

program 30: finding whether a word is palindrome or not

The need:
     In previous posts you have seen that we can have for loop in another for loop. This is true for all the loops and conditional statements also. This is a program for palindrome checking. This program takes some a word as input check whether its a palindrome or not and prints corresponding message for user.

The code: 
--------------------------------------------
#include<stdio.h>
#include<string.h>
main()
{
    int i,j=0,k;
    char a[20];
    printf("Enter a word to check whether its a palindrome.\n");
    scanf("%s",a);
    k=strlen(a);
    for (i=0;i<k/2;i++)
    {
        if(a[i]==a[k-i-1])
        ;                  //empty statement.
        else
         {
          j++;
          break;
         }
    }
    if(j>0)
    printf("The word is not palindrome .\n");
    else
    printf("The word is palindrome .\n");
    getch();
}
-----------------------------------------
 
The approach:     
    Palindrome is the word whose reverse is the same word. So simplest approach is to match first letter to the last, second to second last and so on up to middle. If all are matched, the word is a palindrome else not. The program implements this with the help of single for loop used here.
Here j is an integer variable initialized to 0. Observe if any mismatch is found j is increased. So if at the end of for loop is j is greater than 0, the word is not a palindrome else the word is a palindrome.
    Two more things I wanted to show here. One is that we can have an empty statement. An empty statement is having nothing in it. It is used after if when we want program not to do anything if the condition is satisfied. The second is the 'break' statement. 'break' statement is always used inside a loop. This breaks the loop iterations. So it is used with a condition and breaks the loop flow. Like in our program if is has found a mismatch, there is no need to check further so to save our time it need not run the loop for more number of times. Hence the 'break' statement breaks the loop as soon as the first mismatch is found.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply