-3

I am writing some code to check whether a string is a palindrome, but it's giving me a runtime error. I can't spot where the error is. Please help.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
  char a[20];
  int n,c;
  c=0;
  printf("enter the size of the string  ");
  scanf("%d",&n);
  printf("enter the string ");
  fgets(a,n,stdin);

  for(int i=0;i<(n-1)/2;i++)
  {
      if(a[i]==a[n-1-i])
      {
          c=0;
      }
      else
      {
          c=1;
          break;
      }
  }

  if(c==0)
      printf("string is palindrome");
  else
      printf("string is not palindrome");

  return 0;
}
Pang
  • 9,564
  • 146
  • 81
  • 122
user8971
  • 69
  • 1
  • 4

2 Answers2

1

Well, the first thing I notice, upon compiling and executing this, is that it doesn’t let you enter the string. This is due to the way you’re taking input:

printf("enter the size of the string  ");
scanf("%d",&n);
printf("enter the string ");
fgets(a,n,stdin);

It runs scanf("%d",&n);. So the user types, say, 6, followed by the enter key. Hokay, so scanf looks at those characters 6\n, takes the 6, converts to a number, and n ends up with a value of 6.

But that newline is still there. scanf didn’t do anything with it because it’s not numeric. So, when the code gets to here:

fgets(a,n,stdin);

It then reads that newline and thinks “Okay! The user entered an empty string.” (Yes I know I’m being anthropomorphic, sue me.)

This sort of behavior is why I avoid using scanf. I would code it this way:

fgets(a, sizeof(a), stdin);
n = atoi(a);
printf("enter the string ");
fgets(a, sizeof(a), stdin);

Note that this also limits each fgets to the size of the buffer, avoiding potential buffer overflows. This is an important consideration with working code, because a buffer overflow can easily lead to a vulnerability that can be exploited to break security. Best to develop good habits even with simple learning programs like this.

Note also that a better way to do this would be to simply read the string by itself, then compute its length with strlen.

At this point, it seems to be working correctly, so I won’t delve into the rest of it. However, if you take my advice about computing the length, there’s one more thing to be aware of. If you add this line (temporarily, just for debugging purposes):

printf("%d\n", strlen(a));

You will see that you have one more character than you expect. That is because fgets retains the newline. So, we want to get rid of it:

a[strlen(a) - 1] = '\0';

This isn’t necessary if you use the value of n, because then it will just ignore the newline and use the n characters preceding it. But it would be necessary if you’re computing the length.

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
0

Take a look at this code, that's how I have implemented it (remember to #include <stdbool.h> or it will not work):

for(i = 0; i < string_length; i++)
    {
            if(sentence[i] == sentence[string_lenght-1-i])
                    palindrome = true;
            else
            {
                    palindrome = false;
                    break;
            }
    }

Doing that it will check if your sentence is palindrome and, at the first occurence this is not true it will break the for loop. You can use something like

if(palindrome)
     printf(..);
else
     printf(..);

for a simple prompt for the user.

Example :

radar is palindrome

abba is palindrome

abcabc is not palindrome

Please , pay attention to the fact that

Abba

is not recognized as a palindrome due to the fact that ' A ' and 'a' have different ASCII codes :

'A' has the value of 65

'a' has the value of 97 according to the ASCII table. You can find out more here.

You can avoid this issue trasforming all the characters of the string to lower case characters. You can do this including the <ctype.h> library and calling the function int tolower(int c); like that :

for ( ; *p; ++p) *p = tolower(*p);

or

for(int i = 0; str[i]; i++){
  str[i] = tolower(str[i]);
}

Code by Earlz, take a look at this Q&A to look deeper into that.

EDIT : I made a simple program (however it's a sample, it can be further optimised and so on, it's just to give you the idea), see if it can help you

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>

void LowerCharacters(char *word, int word_lenth);

int main(void){

    char *word = (char *) malloc(10);
    bool palindrome = false;

    if(word == 0)
    {
        printf("\nERROR : Out of memory.\n\n");
        return 1;
    }

    printf("\nEnter a word to check if it is palindrome or not : ");
    scanf("%s", word);

    int word_length = strlen(word);

    LowerCharacters(word,word_length);

    for(int i = 0; i < word_length; i++)
    {
        if(word[i] == word[word_length-1-i])
            palindrome = true;
        else
        {
            palindrome = false;
            break;
        }
    }

    palindrome ? printf("\nThe word %s is palindrome.\n\n", word) : printf("\nThe word %s is not palindrome.\n\n", word);

    free(word);

return 0;

}

void LowerCharacters(char *word, int word_length){

    for(int i = 0; i < word_length; i++)
        word[i] = tolower(word[i]);
}

Input :

Enter a word to check if it is palindrome or not : RadaR

Output :

The word radar is palindrome.

Community
  • 1
  • 1
Claudio Cortese
  • 1,372
  • 2
  • 10
  • 21