CodeBlanks Logo Icon CodeBlanks

ctype.h

  • C course
  • Intermediate
  • Lesson 86/116
  • 5 min

Learn character classification with ctype.h.

ctype.h

The <ctype.h> header provides character classification and conversion functions: isalpha (is letter), isdigit (is digit), toupper (to uppercase) and tolower (to lowercase).

These functions take an int (the numeric value of a char) and return an int. isalpha('A') is true (nonzero), isdigit('5') is true, isdigit('a') is false (0). toupper('a') returns 'A'; if already uppercase it stays the same. tolower does the reverse. For non-ASCII characters these functions depend on the locale; the default C locale handles only ASCII letters. To uppercase a string, we apply toupper to each character in a loop.

Uppercasing a string

To uppercase all letters of a string, we set up a loop and apply toupper to each character. The loop runs until the null character.

Definition: char s[] = "merhaba"; for (int i = 0; s[i]; i++) s[i] = toupper(s[i]);. Here the s[i] condition stops the loop when s[i] is null (0). Each step toupper uppercases the letter and writes it back. Result: MERHABA. This technique is common for text normalization; for example, if you want to compare user input in uppercase, you first uppercase it. The same method with tolower works for lowercase. Modifying character arrays in place saves memory.

Practice Uppercase a string

In main declare char s[] = "merhaba";. In for (int i = 0; s[i]; i++) do s[i] = toupper(s[i]);. After the loop printf("%s\n", s);.

Starter code

main.c
#include <stdio.h>
#include <ctype.h>

// main: char s[] = "merhaba";
// in a for loop uppercase each letter with toupper
// print with printf

int main(void) {
    // write here
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <ctype.h>

int main(void) {
    char s[] = "merhaba";
    for (int i = 0; s[i]; i++) {
        s[i] = toupper(s[i]);
    }
    printf("%s\n", s);
    return 0;
}

Expected output

MERHABA

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 ctype functions

Term Meaning
isalpha is letter
isdigit is digit
toupper to uppercase
tolower to lowercase

2 Convert to uppercase

Question
s[i] = ____(s[i]);
Answer
s[i] = toupper(s[i]);

Explanation: toupper converts a letter to uppercase.

3 What does toupper('a') return?

  • 0
  • 'a'
  • 'A' Correct answer
  • 1

Explanation: toupper converts a lowercase letter to uppercase.

All lessons in Intermediate