Words backwards: palindromes
Go through a word one letter at a time: count its letters and its vowels, write it backwards, and test whether it is a palindrome by comparing letters from both ends at once.
Core concept
A string is a list of characters with indexes from 0; a loop can visit each one in turn, and two pointers moving in from both ends test a palindrome with only half as many comparisons
Topic: Programming basics
In a program, a word or sentence is a string: a list of characters in order. Like any list, each character has an index, starting at 0, so in NEPAL the N is at index 0 and the L at index 4. A loop: Steps that repeat, either a set number of times or until something becomes true. All key words can go through the string one character at a time to count its letters, to count its vowels (A, E, I, O, U), or to build it backwards by putting each new letter in front. A palindrome is a word that reads the same both ways, such as LEVEL or KAYAK. To test one, a program does not need to reverse it: it uses two pointers, i at the start and j at the end, compares the two letters, and moves both inwards. The first pair that differs means it is not a palindrome, and it can stop at once.
What you will learn
- Explain that a string is a list of characters with indexes from 0.
- Trace a loop that counts letters and vowels in a word.
- Build a word backwards one letter at a time.
- Test a palindrome with two pointers and count the comparisons.
Before you start
- Know what a loop is, and that list indexes start at 0.
Materials
- A notebook to write your own palindromes
Equipment
- None
Procedure
- Choose NEPAL and count its vowels.
- Write NEPAL backwards with the reverse task.
- Test LEVEL and NEPAL with the palindrome task.
- Answer the practice challenges.