Coming Soon

This lesson is currently being developed

Chars

Understand character data type and ASCII representation.

Fundamental Data Types
Chapter
Beginner
Difficulty
30min
Estimated Time

What to Expect

Comprehensive explanations with practical examples

Interactive coding exercises to practice concepts

Knowledge quiz to test your understanding

Step-by-step guidance for beginners

Development Status

In Progress

Content is being carefully crafted to provide the best learning experience

Preview

Early Preview Content

This content is still being developed and may change before publication.

4.11 — Chars

In this lesson, you'll learn about the char data type, which stores individual characters, and how to work with characters and text in C++.

What is the char data type?

The char data type stores a single character. Despite being used for text, char is actually an integer type that stores the ASCII (or Unicode) code value of a character.

Think of char like a single letter slot in a typewriter - it can hold exactly one character, whether that's a letter, digit, symbol, or special character.

Basic char usage

#include <iostream>

int main()
{
    // Character literals use single quotes
    char letter = 'A';
    char digit = '5';
    char symbol = '@';
    char space = ' ';
    char newline = '\n';  // Special escape sequence
    
    std::cout << "Character examples:\n";
    std::cout << "Letter: " << letter << std::endl;
    std::cout << "Digit: " << digit << std::endl;
    std::cout << "Symbol: " << symbol << std::endl;
    std::cout << "Space: '" << space << "'" << std::endl;
    std::cout << "Newline creates a new line:" << newline;
    std::cout << "This is on a new line\n";
    
    // Show size of char
    std::cout << "Size of char: " << sizeof(char) << " byte\n";
    
    return 0;
}

Output:

Character examples:
Letter: A
Digit: 5
Symbol: @
Space: ' '
Newline creates a new line:
This is on a new line
Size of char: 1 byte

ASCII values and character codes

Each character has a numeric ASCII code value:

#include <iostream>

int main()
{
    char letter = 'A';
    char digit = '0';
    char symbol = '!';
    
    std::cout << "Characters and their ASCII values:\n";
    
    // Cast char to int to see ASCII value
    std::cout << "'" << letter << "' = " << static_cast<int>(letter) << std::endl;
    std::cout << "'" << digit << "' = " << static_cast<int>(digit) << std::endl;
    std::cout << "'" << symbol << "' = " << static_cast<int>(symbol) << std::endl;
    
    // Create characters from ASCII values
    char fromAscii1 = 65;   // ASCII 65 is 'A'
    char fromAscii2 = 97;   // ASCII 97 is 'a'
    char fromAscii3 = 48;   // ASCII 48 is '0'
    
    std::cout << "\nCharacters from ASCII values:\n";
    std::cout << "ASCII 65: '" << fromAscii1 << "'" << std::endl;
    std::cout << "ASCII 97: '" << fromAscii2 << "'" << std::endl;
    std::cout << "ASCII 48: '" << fromAscii3 << "'" << std::endl;
    
    return 0;
}

Output:

Characters and their ASCII values:
'A' = 65
'0' = 48
'!' = 33

Characters from ASCII values:
ASCII 65: 'A'
ASCII 97: 'a'
ASCII 48: '0'

Escape sequences

Escape sequences represent special characters that are difficult to type or display:

#include <iostream>

int main()
{
    std::cout << "Escape sequences:\n";
    
    // Common escape sequences
    char tab = '\t';
    char newline = '\n';
    char backslash = '\\';
    char quote = '\'';
    char doubleQuote = '\"';
    
    std::cout << "Tab character:" << tab << "creates space\n";
    std::cout << "Newline character:" << newline;
    std::cout << "This is on a new line\n";
    std::cout << "Backslash: " << backslash << std::endl;
    std::cout << "Single quote: " << quote << std::endl;
    std::cout << "Double quote: " << doubleQuote << std::endl;
    
    // Demonstrate practical use
    std::cout << "\nFormatted output example:\n";
    std::cout << "Name:\tJohn Doe\n";
    std::cout << "Age:\t25\n";
    std::cout << "City:\tNew York\n";
    
    std::cout << "\nQuoted text: \"Hello, world!\"\n";
    std::cout << "File path: C:\\Program Files\\MyApp\\\n";
    
    return 0;
}

Output:

Escape sequences:
Tab character:	creates space
Newline character:
This is on a new line
Backslash: \
Single quote: '
Double quote: "

Formatted output example:
Name:	John Doe
Age:	25
City:	New York

Quoted text: "Hello, world!"
File path: C:\Program Files\MyApp\

Character arithmetic

Since char is an integer type, you can perform arithmetic operations:

#include <iostream>

int main()
{
    std::cout << "Character arithmetic:\n";
    
    // Uppercase to lowercase conversion
    char uppercase = 'A';
    char lowercase = uppercase + 32;  // ASCII 'A' + 32 = 'a'
    
    std::cout << "Uppercase: " << uppercase << std::endl;
    std::cout << "Lowercase: " << lowercase << std::endl;
    
    // Better way using ASCII difference
    char upper = 'M';
    char lower = upper + ('a' - 'A');  // Add the difference between 'a' and 'A'
    
    std::cout << "Upper: " << upper << " -> Lower: " << lower << std::endl;
    
    // Digit character to numeric value
    char digitChar = '7';
    int numericValue = digitChar - '0';  // '7' - '0' = 7
    
    std::cout << "Character '" << digitChar << "' as number: " << numericValue << std::endl;
    
    // Number to digit character
    int number = 9;
    char digitCharFromNum = '0' + number;  // '0' + 9 = '9'
    
    std::cout << "Number " << number << " as character: '" << digitCharFromNum << "'" << std::endl;
    
    return 0;
}

Output:

Character arithmetic:
Uppercase: A
Lowercase: a
Upper: M -> Lower: m
Character '7' as number: 7
Number 9 as character: '9'

Character classification

C++ provides functions to check character properties:

#include <iostream>
#include <cctype>  // For character classification functions

int main()
{
    std::cout << "Character classification:\n";
    
    char testChars[] = {'A', 'z', '5', ' ', '@', '\n'};
    int numChars = sizeof(testChars) / sizeof(testChars[0]);
    
    for (int i = 0; i < numChars; ++i)
    {
        char c = testChars[i];
        
        std::cout << "\nCharacter: '";
        if (c == '\n')
            std::cout << "\\n";  // Display newline visibly
        else if (c == ' ')
            std::cout << " ";
        else
            std::cout << c;
        std::cout << "' (ASCII " << static_cast<int>(c) << ")\n";
        
        std::cout << "  Is letter: " << (std::isalpha(c) ? "Yes" : "No") << std::endl;
        std::cout << "  Is digit: " << (std::isdigit(c) ? "Yes" : "No") << std::endl;
        std::cout << "  Is alphanumeric: " << (std::isalnum(c) ? "Yes" : "No") << std::endl;
        std::cout << "  Is uppercase: " << (std::isupper(c) ? "Yes" : "No") << std::endl;
        std::cout << "  Is lowercase: " << (std::islower(c) ? "Yes" : "No") << std::endl;
        std::cout << "  Is whitespace: " << (std::isspace(c) ? "Yes" : "No") << std::endl;
        std::cout << "  Is punctuation: " << (std::ispunct(c) ? "Yes" : "No") << std::endl;
    }
    
    return 0;
}

Output:

Character classification:

Character: 'A' (ASCII 65)
  Is letter: Yes
  Is digit: No
  Is alphanumeric: Yes
  Is uppercase: Yes
  Is lowercase: No
  Is whitespace: No
  Is punctuation: No

Character: 'z' (ASCII 122)
  Is letter: Yes
  Is digit: No
  Is alphanumeric: Yes
  Is uppercase: No
  Is lowercase: Yes
  Is whitespace: No
  Is punctuation: No

Character: '5' (ASCII 53)
  Is letter: No
  Is digit: Yes
  Is alphanumeric: Yes
  Is uppercase: No
  Is lowercase: No
  Is whitespace: No
  Is punctuation: No

Character: ' ' (ASCII 32)
  Is letter: No
  Is digit: No
  Is alphanumeric: No
  Is uppercase: No
  Is lowercase: No
  Is whitespace: Yes
  Is punctuation: No

Character: '@' (ASCII 64)
  Is letter: No
  Is digit: No
  Is alphanumeric: No
  Is uppercase: No
  Is lowercase: No
  Is whitespace: No
  Is punctuation: Yes

Character: '\n' (ASCII 10)
  Is letter: No
  Is digit: No
  Is alphanumeric: No
  Is uppercase: No
  Is lowercase: No
  Is whitespace: Yes
  Is punctuation: No

Character conversion functions

#include <iostream>
#include <cctype>

int main()
{
    std::cout << "Character conversion functions:\n";
    
    char uppercase = 'H';
    char lowercase = 'j';
    char digit = '3';
    char symbol = '#';
    
    std::cout << "Original characters:\n";
    std::cout << "Uppercase: " << uppercase << std::endl;
    std::cout << "Lowercase: " << lowercase << std::endl;
    std::cout << "Digit: " << digit << std::endl;
    std::cout << "Symbol: " << symbol << std::endl;
    
    std::cout << "\nAfter conversion:\n";
    std::cout << "toupper(" << uppercase << ") = " << static_cast<char>(std::toupper(uppercase)) << std::endl;
    std::cout << "tolower(" << uppercase << ") = " << static_cast<char>(std::tolower(uppercase)) << std::endl;
    std::cout << "toupper(" << lowercase << ") = " << static_cast<char>(std::toupper(lowercase)) << std::endl;
    std::cout << "tolower(" << lowercase << ") = " << static_cast<char>(std::tolower(lowercase)) << std::endl;
    std::cout << "toupper(" << digit << ") = " << static_cast<char>(std::toupper(digit)) << " (no change)\n";
    std::cout << "toupper(" << symbol << ") = " << static_cast<char>(std::toupper(symbol)) << " (no change)\n";
    
    return 0;
}

Output:

Character conversion functions:

Original characters:
Uppercase: H
Lowercase: j
Digit: 3
Symbol: #

After conversion:
toupper(H) = H
tolower(H) = h
toupper(j) = J
tolower(j) = j
toupper(3) = 3 (no change)
toupper(#) = # (no change)

Practical applications

Simple text processing

#include <iostream>
#include <cctype>

int main()
{
    std::cout << "Text processing example:\n";
    
    // Analyze a string character by character
    const char* text = "Hello World 123!";
    
    int letters = 0;
    int digits = 0;
    int spaces = 0;
    int others = 0;
    
    std::cout << "Analyzing: \"" << text << "\"\n";
    
    for (int i = 0; text[i] != '\0'; ++i)  // Loop until null terminator
    {
        char c = text[i];
        
        if (std::isalpha(c))
        {
            letters++;
        }
        else if (std::isdigit(c))
        {
            digits++;
        }
        else if (std::isspace(c))
        {
            spaces++;
        }
        else
        {
            others++;
        }
    }
    
    std::cout << "Letters: " << letters << std::endl;
    std::cout << "Digits: " << digits << std::endl;
    std::cout << "Spaces: " << spaces << std::endl;
    std::cout << "Other characters: " << others << std::endl;
    
    return 0;
}

Output:

Text processing example:
Analyzing: "Hello World 123!"
Letters: 10
Digits: 3
Spaces: 1
Other characters: 1

Case conversion utility

#include <iostream>
#include <cctype>

void convertToUppercase(char* str)
{
    for (int i = 0; str[i] != '\0'; ++i)
    {
        str[i] = std::toupper(str[i]);
    }
}

void convertToLowercase(char* str)
{
    for (int i = 0; str[i] != '\0'; ++i)
    {
        str[i] = std::tolower(str[i]);
    }
}

void toggleCase(char* str)
{
    for (int i = 0; str[i] != '\0'; ++i)
    {
        if (std::isupper(str[i]))
        {
            str[i] = std::tolower(str[i]);
        }
        else if (std::islower(str[i]))
        {
            str[i] = std::toupper(str[i]);
        }
    }
}

int main()
{
    // Note: Using char arrays for modification
    char text1[] = "Hello World!";
    char text2[] = "Hello World!";
    char text3[] = "Hello World!";
    
    std::cout << "Original: " << text1 << std::endl;
    
    convertToUppercase(text1);
    std::cout << "Uppercase: " << text1 << std::endl;
    
    convertToLowercase(text2);
    std::cout << "Lowercase: " << text2 << std::endl;
    
    toggleCase(text3);
    std::cout << "Toggled case: " << text3 << std::endl;
    
    return 0;
}

Output:

Original: Hello World!
Uppercase: HELLO WORLD!
Lowercase: hello world!
Toggled case: hELLO wORLD!

Simple Caesar cipher

#include <iostream>
#include <cctype>

char caesarShift(char c, int shift)
{
    if (std::isalpha(c))
    {
        char base = std::isupper(c) ? 'A' : 'a';
        return ((c - base + shift) % 26) + base;
    }
    return c;  // Non-alphabetic characters remain unchanged
}

void encryptCaesar(char* text, int shift)
{
    for (int i = 0; text[i] != '\0'; ++i)
    {
        text[i] = caesarShift(text[i], shift);
    }
}

int main()
{
    char message[] = "Hello World!";
    int shift = 3;
    
    std::cout << "Caesar Cipher Example:\n";
    std::cout << "Original: " << message << std::endl;
    
    encryptCaesar(message, shift);
    std::cout << "Encrypted (shift " << shift << "): " << message << std::endl;
    
    // Decrypt by shifting back
    encryptCaesar(message, -shift);
    std::cout << "Decrypted: " << message << std::endl;
    
    return 0;
}

Output:

Caesar Cipher Example:
Original: Hello World!
Encrypted (shift 3): Khoor Zruog!
Decrypted: Hello World!

signed char vs unsigned char

The char type can be signed or unsigned (implementation-dependent):

#include <iostream>
#include <climits>

int main()
{
    std::cout << "char type variations:\n";
    
    // Regular char (implementation-dependent signedness)
    char regularChar = 200;
    
    // Explicitly signed char
    signed char signedChar = 200;  // May be negative due to overflow
    
    // Explicitly unsigned char
    unsigned char unsignedChar = 200;
    
    std::cout << "Regular char value: " << static_cast<int>(regularChar) << std::endl;
    std::cout << "Signed char value: " << static_cast<int>(signedChar) << std::endl;
    std::cout << "Unsigned char value: " << static_cast<int>(unsignedChar) << std::endl;
    
    std::cout << "\nRanges:\n";
    std::cout << "char range: " << CHAR_MIN << " to " << CHAR_MAX << std::endl;
    std::cout << "signed char range: " << SCHAR_MIN << " to " << SCHAR_MAX << std::endl;
    std::cout << "unsigned char range: 0 to " << UCHAR_MAX << std::endl;
    
    return 0;
}

Typical Output:

char type variations:
Regular char value: -56
Signed char value: -56
Unsigned char value: 200

Ranges:
char range: -128 to 127
signed char range: -128 to 127
unsigned char range: 0 to 255

Best practices with char

✅ Use single quotes for character literals

char letter = 'A';     // Correct
// char letter = "A";  // Wrong! This is a string literal

✅ Use escape sequences for special characters

char tab = '\t';
char newline = '\n';
char quote = '\'';
char backslash = '\\';

✅ Use character classification functions

#include <cctype>

// Good: Use standard library functions
if (std::isalpha(c)) { /* ... */ }
if (std::isdigit(c)) { /* ... */ }

// Avoid: Manual range checking
// if (c >= 'A' && c <= 'Z') { /* ... */ }  // Doesn't work for all character sets

✅ Be careful with char arithmetic

// Good: Safe character operations
char upper = 'A';
char lower = std::tolower(upper);

// Risky: Direct arithmetic (assumes ASCII)
// char lower = upper + 32;  // May not work with all character encodings

Summary

The char data type is fundamental for text processing:

Key concepts:

  • Stores single characters using ASCII (or Unicode) values
  • Actually an integer type (1 byte)
  • Character literals use single quotes: 'A', '5', '@'
  • Escape sequences represent special characters: '\n', '\t', '\''

Character operations:

  • Classification: isalpha(), isdigit(), isspace(), etc.
  • Conversion: toupper(), tolower()
  • Arithmetic: possible but use with caution

Variations:

  • char: implementation-dependent signedness
  • signed char: guaranteed signed (-128 to 127)
  • unsigned char: guaranteed unsigned (0 to 255)

Best practices:

  • Use single quotes for character literals
  • Use standard library functions for character operations
  • Be aware of character encoding assumptions
  • Use escape sequences for special characters

Quiz

  1. What's the difference between 'A' and "A"?
  2. What ASCII value does the character '0' have?
  3. How do you convert a lowercase letter to uppercase using arithmetic?
  4. What does the escape sequence '\n' represent?
  5. What's the difference between char, signed char, and unsigned char?

Practice exercises

Try these character exercises:

  1. Write a function that counts vowels in a string
  2. Create a program that validates if a character is a valid hexadecimal digit
  3. Implement a ROT13 cipher (shift each letter by 13 positions in the alphabet)
  4. Write a function that removes all non-alphabetic characters from text

Continue Learning

Explore other available lessons while this one is being prepared.

View Course

Explore More Courses

Discover other available courses while this lesson is being prepared.

Browse Courses

Lesson Discussion

Share your thoughts and questions

💬

No comments yet. Be the first to share your thoughts!

Sign in to join the discussion