Does C and C++ ensure the ASCII codes for a-z and A-Z characters?
The ASCII codes for lowercase letters “a-z” and uppercase letters “A-Z” are consistent across various systems and programming languages, including C/C++. This consistency ensures that the ASCII codes of these characters remain the same on any system that supports ASCII encoding. The ASCII ranges for uppercase and lowercase letters is given below:
ASCII Range for Upper and Lowercase Letters
Upper letters | ASCII values range |
A–Z | 65–90 |
Lower letters | ASCII values range |
a–z | 97–122 |
Moreover, as the ASCII codes for these characters are sequential and ascending, we can use a loop in C/C++ to iterate through, as follows:
#include <iostream>using namespace std;int main() {char symbol;// print ASCII values of A-Zfor (symbol = 'A'; symbol <= 'Z'; symbol++){cout << symbol << ": " << (int)symbol <<endl;}// print ASCII values of a-zfor (symbol = 'a'; symbol <= 'z'; symbol++){cout << symbol << ": " << (int)symbol <<endl;}return 0;}
Explanation
-
Line 5: A variable named
symbolof typecharis declared to store characters. -
Line 8–11: This block of code represents a
forloop that iterates over the uppercase letters fromAtoZ. It initializes symbol withAand continues the loop as long as symbol is less than or equal toZ. In each iteration, it prints the current value ofsymbol, followed by a colon and the ASCII value of the character obtained by castingsymbolto an integer using(int)symbol. -
Line 14–17: This block of code represents another
forloop that iterates over the lowercase letters fromatoz. It initializessymbolwithaand continues the loop as long assymbolis less than or equal toz. In each iteration, it prints the current value ofsymbol, followed by a colon and the ASCII value of the character obtained by castingsymbolto an integer using(int)symbol.
Free Resources