C Program to Convert Uppercase to Lowercase
32 if it is uppercase, like if(c >= 'A' && c <= 'Z') c = c + 32;.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { char str[100]; int i = 0; printf("Enter a string: "); fgets(str, sizeof(str), stdin); while (str[i] != '\0') { if (str[i] >= 'A' && str[i] <= 'Z') { str[i] = str[i] + 32; } i++; } printf("Lowercase string: %s", str); return 0; }
Dry Run
Let's trace the input 'HELLO' through the code
Input string
str = 'HELLO\n'
Check first character 'H'
'H' is between 'A' and 'Z', so convert: 'H' + 32 = 'h'
Check second character 'E'
'E' is uppercase, convert to 'e'
Check third character 'L'
'L' is uppercase, convert to 'l'
Check fourth character 'L'
'L' is uppercase, convert to 'l'
Check fifth character 'O'
'O' is uppercase, convert to 'o'
End of string
Stop at '\0' character
| Index | Original Char | Is Uppercase? | Converted Char |
|---|---|---|---|
| 0 | H | Yes | h |
| 1 | E | Yes | e |
| 2 | L | Yes | l |
| 3 | L | Yes | l |
| 4 | O | Yes | o |
Why This Works
Step 1: Check uppercase range
The code uses if(c >= 'A' && c <= 'Z') to find uppercase letters because uppercase letters are continuous in ASCII.
Step 2: Convert by adding 32
Adding 32 to the ASCII value converts uppercase letters to lowercase since 'a' is 32 positions after 'A'.
Step 3: Process each character
The program loops through each character to convert all uppercase letters in the string.
Alternative Approaches
#include <stdio.h> #include <ctype.h> int main() { char str[100]; int i = 0; printf("Enter a string: "); fgets(str, sizeof(str), stdin); while (str[i] != '\0') { str[i] = tolower(str[i]); i++; } printf("Lowercase string: %s", str); return 0; }
#include <stdio.h> int main() { char str[100]; int i = 0; printf("Enter a string: "); fgets(str, sizeof(str), stdin); while (str[i] != '\0') { if (str[i] >= 'A' && str[i] <= 'Z') { str[i] = str[i] | 32; } i++; } printf("Lowercase string: %s", str); return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through each character once, so time complexity is O(n) where n is the string length.
Space Complexity
The conversion is done in-place without extra memory, so space complexity is O(1).
Which Approach is Fastest?
Using bitwise OR is fastest due to low-level operation, but using tolower() is safer and more readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual ASCII check and add 32 | O(n) | O(1) | Simple, clear logic |
| Using tolower() function | O(n) | O(1) | Safety and locale support |
| Bitwise OR with 32 | O(n) | O(1) | Performance and low-level optimization |