C bootcamp · Lab 19

Palindrome check

mediumStrings12 minLesson: Strings

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read one word and print yes if it reads the same forwards and backwards, otherwise no.

Ignore case: Level should count as a palindrome.

Input. One line: a word.

Output. yes or no (lowercase).

Examples

Example 1 — Case-insensitive.
Input
Level
Output
yes
Example 2
Input
python
Output
no
Hint
  1. Walk two indices inward: one from the front, one from the back.
  2. Compare tolower(s[i]) with tolower(s[n-1-i]); if any pair differs, it is not a palindrome.
Show correct code

Peek only after you have tried. You can still Check your own version.

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

int main(void) {
  char s[1024];
  if (scanf("%1023s", s) != 1) { printf("no\n"); return 0; }
  int n = strlen(s), ok = 1;
  for (int i = 0; i < n / 2; i++) {
    if (tolower((unsigned char)s[i]) != tolower((unsigned char)s[n - 1 - i])) { ok = 0; break; }
  }
  printf(ok ? "yes\n" : "no\n");
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.