Adsense 728 * 15

Search

Custom Search

C, C++ Program to Check whether a String is Palindrome or not

Write a C, C++ program to check whether a string is palindrome or not. Given an input string, we have to write a code to check whether a input string is palindrome or not. 

Program to check whether a number is palindrome or not

Programming questions on strings

what is Palindrome ?

Palindrome is a word, phrase, or sequence that reads the same backwards as forwards.

For example - Nitin, Madam etc. If you reverse word Madam it's still remains the same.



Algorithm to Check whether String is Palindrome or not

Traverse a string from both the ends and compare if char on both the indexes are equal. If character on both the indexes are equal then it's a palindrome.  Let's implement it.

1. Take two indexes.

     int start = 0;
     int end = strlen - 1;


2. Traverse a string from both the ends and compare. If  start and end indexes of a string is  equal then it's a palindrome.






Program to Check Whether a String is Palindrome in C

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

int main()
{
   char str[100];
   
   /* Take input string from user. */

   printf("Enter a string");
   gets(str);
   
   int start=0,flag=0;
   int end = strlen(str)-1;
   
   /* start index is less than end index. */
   
   while(start < end){
       
       /* If start and end char is equal. */
       
       if(str[start]==str[end]){
           
           flag=1;
           
       }else {
           
           flag=0;
           break;
       }
       
       start++;
       end--;
   }
   
   if(flag){ 

       printf("String is a palindrome");
   
   }else{

       printf("String is not a palindrome");
   }
   
    return 0;
}



Output:

Enter a string :  Rar

String is a palindrome

Program to Check whether a String is Palindrome or not in C++


#include <iostream>
#include <string.h>

using namespace std;

int main() {

    /* String declaration */

    char str[100];

    int start, end, flag = 1;

    /* Take input string from a user */

    cout << "Please enter a string ";
    cin >> str;

    // Assign the value of two indexes
    
    start = 0;
    end   = strlen(str) - 1;

    /* start index is less than end index. */

    while (start < end) {

        /* If start and end char of a string
           is not equal then break a loop */

        if (str[start] != str[end]) {

            flag = 0;
            break;

        }

        start++;
        end--;
    }

    if (flag) {

        cout << "Input string is a palindrome";

    } else {

        cout << "Input string is not a palindrome";

    }

    return 0;
}


Programming question on Arrays

Programming question on Linked List

Sorting algorithm and their time complexity

Stack implementation

Programming questions using Recursion

C, C++ interview questions

Programming Books

No comments:

Post a Comment