C Workshop · Palindrome Check
Lesson C

Palindrome Check

A palindrome reads the same forwards and backwards. Compare opposite ends until they meet.

What it is

A palindrome reads the same forwards and backwards. You compare the first letter to the last, then step inward. If every pair matches, the word is a palindrome. level is yes; hello is no.

Approach

  1. Read the word. Find n = strlen(s).
  2. for i from 0 while i < n-1-i, compare s[i] and s[n-1-i].
  3. If all pairs match, Yes; else No.

Where this is used in the real world

Diagram

1

l…l

ok

2

e…e

ok

3

v

middle

4

Yes

output

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2#include <string.h>
3int main(void) {
4    char s[64];
5    int i, n, ok = 1;
6    scanf("%63s", s);
7    n = (int)strlen(s);
8    for (i = 0; i < n - 1 - i; i++) {
9        if (s[i] != s[n - 1 - i]) ok = 0;
10    }
11    printf("%s\n", ok ? "Yes" : "No");
12    return 0;
13}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. level prints:

All pairs match.

2. hello would print:

h != o.

3. The middle letter of odd length:

i < n-1-i stops at the middle.

4. ok starts as 1 meaning:

Flag.

5. You could also reverse into another buffer and strcmp. That would:

Two algorithms, one question.