C Program to Check a Palindrome String

The program to check a string for palindrome is written using Dev-C++ version 4 compiler installed on a Windows 7 64-bit system.

You can use any standard C compiler to compile the program and it will still work.This program is intended for beginners who are learning C programming language.

In sections below, we have given the problem definition, flowchart for the program, source code, and verified output after running the program successfully.

Problem Definition

A palindrome string is a special string which is same when you read it from left-to-right or right-to-left.

For example, the string “ToboT“, is same if you read it from left-to-right or right-to-left, therefore, it is a Palindrome.

In this program, we will read a input string and check if it is a palindrome string and display the output to the console.

How to process the input string?

The steps to check the input string is given below.

Step 1 – Read the input string

Step 2 – Read the input string from left-to-right & right-to-left character by character.

Step 3 – Compare each character of left side to the right side character one at a time.

Step 4 – If any character is different, set flag = 1, else flag = 0.

Step 5 – If flag = = 0, print “It is a Palindrome“.

Step 6 – Finally, if flag = = 1, print” It is not a Palindrome“.

Step 7 – End the program.

Flowchart – C Program to Check a Palindrome String

Flowchart - C Program for Palindrome Check
Flowchart – C Program for Palindrome Check

Program Code – Palindrome String

/*Program to Check if the String is Palindrome or not */

#include <stdio.h>
#include <conio.h>

main()
{

    char string [80],c;
    int i,j,len,flag=0;


    /* Read the string */


    printf("Enter a String for 
            Palindrome Check:\n\n");

    scanf("%[^n]",string);

    printf("%s",string);


    /* Find length of the string */


    for(len=0;string[len]!='\0';len++)

    printf("\n\nLength is %d\n",len);


    /* Double initialisation for FOR loop */


    for(i=0,j=len-1;i<len/2;i++,j--)
    {

        if(string[i]!=string[j])
            flag=1;

    }

/* Check if Palindrome and print the result */


    if(flag)
    {

      for(i=1;i<=30;i++)
      printf("_");printf("\n\n");

      printf("\nString is a not Palindrome.\n");

      for(i=1;i<=30;i++)
      printf("_");printf("\n\n");

    }
    else
    {

      for(i=1;i<=30;i++)
      printf("_");printf("\n\n");

      printf("\nString is a Palindrome.\n");

      for(i=1;i<=30;i++)
      printf("_");printf("\n\n");

    }

    system("PAUSE");
    return 0;
}

Output

The output of the program is given below. The program reads a string called “TaboT” and prints the output to the console.

Output - C Program to Check a Palindrome String
Output – C Program to Check a Palindrome String
Advertisements