0

Hey i'm new in that community, so maybe that question was probably already asked before. Also before we get to the Problem, My Code is created to identify if a word is a palindrome or not. so here is the problem, my code works fine, but i would like to have to repeat this word-identify 5 times also like a loop in example.

#include <stdio.h>

int main()
{
  char text[100];
  int beg, mid, end, len = 0;

  gets(text);

  while (text[len] != '\0')
    len++;

  end = len - 1;
  mid = len/2;

  for (beg = 0; beg < mid; beg++)
  {
    if (text[beg] != text[end])
    {
      printf("This is not a palindrome.\n");
      break;
    }
    end--;
  }
  if (beg == mid)
    printf("This word is a Palindrome.\n");

  return 0;
}
David
  • 21
  • 3
  • 4
    Never ***ever*** use `gets`. It's a [dangerous](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) function that have even been removed from the C language. Use e.g. [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead, but be aware of the differences from `gets`. – Some programmer dude Apr 09 '19 at 17:07
  • 2
    Also don't write your own code for things that exists in the standard C library, like e.g. [`strlen`](https://en.cppreference.com/w/c/string/byte/strlen). – Some programmer dude Apr 09 '19 at 17:08
  • I'll thank you for your advice, now i know what i should note in programming C for the next time. – David Apr 09 '19 at 17:55

2 Answers2

0

I would do so:

#include <stdio.h>

int
checkPalindrome(char * inputString) {
  char *temp = inputString+strlen(inputString)-1;
  while (temp>inputString)
    if (*temp--!=*inputString++)
      return 0;
  return 1;
}


void main()
{
  char text[100];
  int count=0;

  while(count++ != 5)
  {
     printf("Enter word: \n");
     scanf("%s", text);
     if (checkPalindrome(text)
       printf("This word is a Palindrome.\n");
  }
}
alinsoar
  • 15,386
  • 4
  • 57
  • 74
0

All you need to do is have a variable that starts at the beginning of the array, and one that starts at the end, and loop through until they're equal to each other. Beyond that the validity of the word is already confirmed.

int main()
{            
    char text[100];
    int start = 0;
    int end = sizeof(text) - 1;
    bool isPalendrome = true;

    while(start <= end)
    {
        var char1 = text[start];
        var char2 = text[end];

        if(char1 == char2)
        {
            start++;
            end--;
        }
        else
        {
            printf("This word is not a palindrome");
            isPalindrome = false;
            break;
        }
    }

    if(isPalindrome) 
    {
        printf("Word is a palindrome");
    }

    return 0;
}
Dortimer
  • 619
  • 8
  • 25
  • Did you look through any error messages? I just noticed I had missed a semi-colon in there, and I updated the answer accordingly. – Dortimer Apr 10 '19 at 14:00