Tuesday 26 March 2019

CP: Palindrome string or not ?

Que: Write a program to check whether the entered string is palindrome or not.


A palindrome is a string, which when read in both forward and backward way is the same.
Example: radar, madam, pop, lol

To compare it with the reverse of itself, the following logic is used:
  1. 0th character in the char array, string1 is same as 4th character in the same string.
  2. 1st character is same as 3rd character.
  3. 2nd character is same as 2nd character.
  4. . . . .
  5. ith character is same as 'length-i-1'th character.
  6. If any one of the above condition fails, flag is set to true(1), which implies that the string is not a palindrome.
  7. By default, the value of flag is false(0). Hence, if all the conditions are satisfied, the string is a palindrome.

Code: 


#include <stdio.h>
#include <string.h>

int main(){
    char string1[20];
    int i, length;
    int flag = 0;

    printf("\nEnter a string:");
    scanf("%s", string1);

    length = strlen(string1);

    for(i=0;i < length ;i++)
        {
        if(string1[i] != string1[length-i-1])
        {
            flag = 1;
            break;
        }
        }

    if (flag) 
        {
        printf("\n%s is not a palindrome\n", string1);
        }
    else 
       {
        printf("\n%s is a palindrome\n", string1);
       }
    return 0;
}

Output: 




No comments:

Post a Comment

LAB 7 Arduino with Seven Segment Display || Arduino Tutorial || Code and Circuit Diagram || Project

  LAB 7 Arduino with Seven Segment Display || Arduino Tutorial || Code and Circuit Diagram || Project Dear All We will learn how to Connec...