Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

Palindromes using C programming

(Palindromes) A palindrome is a string that is spelled the same way forward and backward.
Some examples of palindromes are: “radar,” “able was i ere i saw elba,” and, if you ignore blanks, “a
man a plan a canal panama.” Write a recursive function testPalindrome that returns 1 if the string
stored in the array is a palindrome and 0 otherwise. The function should ignore spaces and punctuation
in the string.

Answer:


#include <stdio.h>
#define SIZE 80

// function prototype
int testPalindrome( char array[], int left, int right );

int main( void )
{ 
   char c; // temporarily holds keyboard input 
   char string[ SIZE ]; // original string
   char copy[ SIZE ]; // copy of string without spaces
   unsigned int count = 0; // length of string
   unsigned int copyCount; // length of copy
   unsigned int i; // counter

   puts( "Enter a sentence:" );

   // get sentence to test from user
   while (  (  c = getchar()  ) != '\n' && count < SIZE )
 { string[ count++ ] = c; } // end while 
string[ count ] = '\0'; // terminate string
 // make a copy of string without spaces
 for ( copyCount = 0, i = 0; string[ i ] != '\0'; ++i ) 
{ if ( string[ i ] != ' ' && string[ i ] != ',' && string[ i ] != '.' && string[ i ] != '!' ) 
{ copy[ copyCount++ ] = string[ i ]; } // end if
 } // end for
 // print whether or not the sentence is a palindrome 
if ( testPalindrome( copy, 0, copyCount - 1 ) )
 { printf( "\"%s\" is a palindrome\n", string ); } // end if else 
{ printf( "\"%s\" is not a palindrome\n", string ); } // end else
 } // end main
 // function to see if the sentence is a palindrome 
int testPalindrome( char array[], int left, int right ) 
{ // test array to see if a palindrome 
if ( left == right || left > right ) {
      return 1;
   } // end if
   else if ( array[ left ] != array[ right ] ) {
      return 0;
   } // end else if
   else {
      return testPalindrome( array, left + 1, right - 1 );
   } // end else
}

About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!