LearnStanmorephysics

Grade 11 · Powering Up

Ord, Chr and secret codes

Grade 11 · String manipulation · Lesson and coding task · about 16 minutes

Open this task in the Delphi workspace →

Every character has a number — its ASCII/ordinal value. Ord('A') is 65, Ord('B') is 66 … and Chr(65) turns 65 back into 'A'. Which means you can do maths on letters:

Chr(Ord('A') + 1)    // 'B'  - the next letter

That is the engine of the Caesar cipher: shift every letter along the alphabet. One problem — shift 'Z' by 3 and you fall off the end. The fix is to wrap around:

iCode := Ord(cLetter) + iShift;
if iCode > Ord('Z') then
  iCode := iCode - 26;         // wrap Z back to A

To decide whether a character even is a letter, use a set: if cLetter in ['A'..'Z'] then … — anything else (spaces, digits) passes through unchanged.

Your task

Encrypt a message: uppercase it, shift each letter by the given amount (wrapping after Z), and leave non-letters alone.

Exam tip. Encryption questions are PAT and Paper 1 favourites. Learn the wrap-around IF by heart — it is nearly always the mark you drop.

What you will do

Hints
  1. Test for a letter with if cLetter in ['A'..'Z'] then
  2. Shift: iCode := Ord(cLetter) + iShift; then if iCode > Ord('Z') then iCode := iCode - 26;
  3. Build the answer like a running total: sCode := sCode + Chr(iCode);
Model solution
procedure TfrmSecret.btnEncodeClick(Sender: TObject);
var
  sWord, sCode : String;
  i, iShift, iCode : Integer;
  cLetter : Char;
begin
  sWord := UpperCase(edtWord.Text);
  iShift := StrToInt(edtShift.Text);
  sCode := '';
  for i := 1 to Length(sWord) do
  begin
    cLetter := sWord[i];
    if cLetter in ['A'..'Z'] then
    begin
      iCode := Ord(cLetter) + iShift;
      if iCode > Ord('Z') then
        iCode := iCode - 26;
      sCode := sCode + Chr(iCode);
    end
    else
      sCode := sCode + cLetter;
  end;
  lblCode.Caption := sCode;
end;

About this material

This platform provides original CAPS-aligned practice material and study tools. Content is machine-verified and has not been reviewed by subject specialists. It is not affiliated with or endorsed by the Department of Basic Education. Learners should also use official past papers and consult their teachers where uncertain.