C Program to Convert String to Lowercase
tolower() function from ctype.h, like this: str[i] = tolower(str[i]); inside a loop.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> #include <ctype.h> int main() { char str[] = "HeLLo WoRLd!"; for (int i = 0; str[i] != '\0'; i++) { str[i] = tolower((unsigned char)str[i]); } printf("%s\n", str); return 0; }
Dry Run
Let's trace the string "HeLLo WoRLd!" through the code
Start with first character
Character 'H' is uppercase, convert to 'h'
Next characters
Characters 'e', 'L', 'L', 'o' converted to 'e', 'l', 'l', 'o' respectively
Continue to end
Spaces and punctuation remain unchanged; uppercase letters converted
| Index | Original Char | Converted Char |
|---|---|---|
| 0 | H | h |
| 1 | e | e |
| 2 | L | l |
| 3 | L | l |
| 4 | o | o |
| 5 | ||
| 6 | W | w |
| 7 | o | o |
| 8 | R | r |
| 9 | L | l |
| 10 | d | d |
| 11 | ! | ! |
Why This Works
Step 1: Using tolower()
The tolower() function converts uppercase letters to lowercase and leaves other characters unchanged.
Step 2: Looping through string
We loop through each character until we reach the string's end marked by \0.
Step 3: In-place modification
We replace each character in the original string with its lowercase version directly.
Alternative Approaches
#include <stdio.h> int main() { char str[] = "HeLLo WoRLd!"; for (int i = 0; str[i] != '\0'; i++) { if (str[i] >= 'A' && str[i] <= 'Z') { str[i] = str[i] + ('a' - 'A'); } } printf("%s\n", str); return 0; }
#include <stdio.h> #include <ctype.h> int main() { char str[] = "HeLLo WoRLd!"; char lower[100]; int i = 0; while (str[i] != '\0') { lower[i] = tolower((unsigned char)str[i]); i++; } lower[i] = '\0'; printf("%s\n", lower); return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The code loops through each character once, so time grows linearly with string length.
Space Complexity
The conversion is done in-place, so no extra space is needed beyond the input string.
Which Approach is Fastest?
Using tolower() is efficient and readable; manual ASCII conversion is similar in speed but less clear; creating a new string uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using tolower() | O(n) | O(1) | Simple and safe in-place conversion |
| Manual ASCII conversion | O(n) | O(1) | Avoids library but less readable |
| New lowercase string | O(n) | O(n) | Preserving original string, uses extra memory |
ctype.h and use tolower() for safe and simple lowercase conversion.\0 causes infinite loops or crashes.