Sunday 1 October 2017

How to check Palindrome

Check if a string is palindrome or not is one of most common question we encountered during our basic days.

Let's Solve this problem with a Naive but efficient approach in this case.

Pseudocode :

  1. i=0, j=n
  2. while i < j:
  3.    check if i'th element is not equal to j'th
  4.      then return False 
  5.   else i++,j--
  6. loop end
  7. return True


Source Code in C:

We implemented both versions of palindrome check using for loop and while loop.


  1. #include<stdio.h>
  2. int isPalindrome(char arr[],int size){
  3.     //Using for loop
  4.     int i,j;
  5.     for(i=0,j=size-1;i<j;i++,j--){
  6.         if(arr[i] != arr[j]){
  7.             return 0;
  8.         }
  9.     }
  10.     return 1;
  11. }
  12. int isPalindrome2(char arr[],int size){
  13.     //using While loop
  14.     int i,j;
  15.     i=0;
  16.     j=size-1;
  17.     while(i<j){
  18.         if(arr[i] != arr[j]){
  19.             return 0;
  20.         }
  21.         else{
  22.             i++;
  23.             j--;
  24.         }
  25.     }
  26.     return 1;
  27. }
  28. int main(){
  29.     char arr[4]={"abba"};
  30.     char arr2[5]={"abvba"};
  31.    
  32.     if(isPalindrome(arr,4)){
  33.         printf("\n%s : is a Palindrome",arr);
  34.     }else{
  35.         printf("\nIt is NOT a Palindrome");
  36.     }
  37.    
  38.     if(isPalindrome2(arr2,5)){
  39.         printf("\n%s : is a Palindrome",arr2);
  40.     }else{
  41.         printf("\nIt is NOT a Palindrome");
  42.     }
  43. }
Output:
isPalindrome

2 comments:

  1. Thank you for this interesting small tip! Such little actions can fasten my working process twice! I really believe that this information is a future of language translation and a lot of people will use it in future. Thank you for making this early review.

    ReplyDelete

THANKS FOR UR GREAT COMMENT

Blogger Widgets