76. Convert Uppercase Letters to Lowercase

#include <stdio.h>
#include <stdint.h>

// Function to convert all uppercase characters in the string to lowercase
void to_lowercase(char *str) {
    uint8_t i = 0;
    while (str[i] != '\0') {
        // Check if the character is uppercase A–Z using ASCII range
        if (str[i] >= 'A' && str[i] <= 'Z') {
            str[i] += 32; // Convert to lowercase by adding ASCII offset
        }
        i++;
    }
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove trailing newline character from input
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    to_lowercase(str);
    printf("%s", str);
    return 0;
}

Conceptual Understanding:

In C, every character is represented by an ASCII value. The uppercase letters (A to Z) fall in the ASCII range 65 to 90.

The corresponding lowercase letters (a to z) are in the range 97 to 122. The difference between them is exactly 32.

For example:

  • 'A' (ASCII 65) → 'a' (ASCII 97)
  • 'B' (ASCII 66) → 'b' (ASCII 98)

    … and so on.
     

So, to convert any uppercase letter to lowercase, we can add 32 to its ASCII value.

Firmware Importance:

  • Embedded systems often process user input from UART or serial terminals
  • Normalizing commands (e.g., "SET" and "set") requires reliable lowercase conversion
  • Avoids relying on standard libraries (ctype.h), which may be unavailable or memory-heavy
  • Critical for building reliable CLI, AT-command parsers, or configuration shells

Implementation Logic:

  • Traverse the input string using a loop
  • For each character, check if it lies in 'A' to 'Z'
  • If yes, convert it by adding 32
  • The logic works in-place using a single loop and no extra buffer

     
Loading...

Input

Hello Embedded

Expected Output

hello embedded