C/C++ Arena

Step 5 of 6

Characters with char

A char holds a single character, such as a letter, digit or symbol. Character values are written in single quotes: 'A', '7', '?'. Double quotes mean something different: "A" is a string (text that can have many characters), which you'll meet properly later.

Print a char with %c:

#include <stdio.h>

int main(void) {
    char grade = 'B';
    char next = grade + 1;
    printf("Grade: %c\n", grade);
    printf("Next: %c\n", next);
    printf("As a number: %d\n", grade);
    return 0;
}
Grade: B
Next: C
As a number: 66

Characters are numbers

Computers only store numbers, so every character has a numeric code. The standard table is called ASCII: 'A' is 65, 'B' is 66, 'a' is 97, '0' is 48, and a space is 32. A char is really a small integer (one byte), and C lets you do arithmetic on it, which is why grade + 1 gives 'C'.

What you see depends on how you print it: %c shows the character, %d shows its code. It's the same value either way.

Common mistakes

Your task

Write a program that stores the letter T in a char named team, then prints two lines:

Team: T
Code: 84

Challenge 2

Store the letter A in a char named grade and print it as a letter, so the output is Grade: A.

Challenge 3

Characters are small numbers, so you can do arithmetic on them. Store 'a' in a char named key, then print the key and the letter that comes after it by adding 1:

Key: a
Next: b

Previous: Decimals with double Next: Constants and sizeof