Arithmetic with characters
What you'll learn: How to perform mathematical operations on letters by treating them as their underlying numeric ASCII values.
Letters are just numbers in disguise
In C, a char is actually a small integer hiding behind a symbol. When you type 'A', the computer sees the number 65. Because of this, C allows you to perform math directly on characters. If you take the letter 'A' and add 1 to it, you don't get an error; you simply get the next number in the sequence (66), which the computer interprets as 'B'.
Think of the ASCII table like a numbered rack of cubbies in a post office. If you are standing at the cubby labeled 'A' (number 65) and take one step to the right, you are now at cubby 66.
Using math to shift characters
This behavior is incredibly useful for manipulating text. For example, if you want to convert a lowercase letter to an uppercase one, you don't need a complex lookup table. You just need to know that the distance between 'a' and 'A' is always the same (32). By subtracting 32 from any lowercase letter, you "jump" across the ASCII table to its uppercase equivalent.
Likewise, you can use arithmetic to transform digits stored as characters (like '5') into their actual integer values (like 5) by subtracting the character '0'.
Example: Shifting through the alphabet
Here is how you can manipulate characters using standard math operators:
#include <stdio.h>
int main() {
char letter = 'C';
// Move forward two spots in the alphabet
char nextLetter = letter + 2;
printf("Two steps after C is: %c\n", nextLetter); // Outputs 'E'
// Find the distance between two letters
int distance = 'Z' - 'A';
printf("Distance between A and Z: %d\n", distance); // Outputs 25
// Lowercase to Uppercase shortcut
char lower = 'g';
char upper = lower - 32;
printf("Uppercase of g is: %c\n", upper); // Outputs 'G'
return 0;
}
Why this matters
Character arithmetic is the foundation of many text-based features, such as building simple ciphers (like the Caesar Cipher), sorting words alphabetically, or validating user input. As long as you remember that 'A' + 1 equals 'B', you can navigate the entire alphabet using nothing but a plus or minus sign.
Key takeaway
In C, characters are numeric values, allowing you to use addition and subtraction to navigate the alphabet or transform text.