C Program to Convert Lowercase to Uppercase
if(c >= 'a' && c <= 'z') c = c - 32;.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { char str[100]; printf("Enter a string: "); fgets(str, sizeof(str), stdin); for (int i = 0; str[i] != '\0'; i++) { if (str[i] >= 'a' && str[i] <= 'z') { str[i] = str[i] - 32; } } printf("Uppercase string: %s", str); return 0; }
Dry Run
Let's trace the input 'hello' through the code
Input string
str = 'hello\0'
Check first character 'h'
'h' is between 'a' and 'z', so convert: 'h' (ASCII 104) - 32 = 'H' (ASCII 72)
Check second character 'e'
'e' is lowercase, convert to 'E'
Check third character 'l'
'l' is lowercase, convert to 'L'
Check fourth character 'l'
'l' is lowercase, convert to 'L'
Check fifth character 'o'
'o' is lowercase, convert to 'O'
End of string
Stop loop at '\0'
| Index | Original Char | Is Lowercase? | 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 if character is lowercase
The code uses if (str[i] >= 'a' && str[i] <= 'z') to find lowercase letters because ASCII codes for 'a' to 'z' are continuous.
Step 2: Convert by subtracting 32
Subtracting 32 from the ASCII value converts a lowercase letter to uppercase since uppercase letters are 32 positions before lowercase in ASCII.
Step 3: Leave other characters unchanged
Characters outside 'a' to 'z' range remain the same, so numbers and symbols are not affected.
Alternative Approaches
#include <stdio.h> #include <ctype.h> int main() { char str[100]; printf("Enter a string: "); fgets(str, sizeof(str), stdin); for (int i = 0; str[i] != '\0'; i++) { str[i] = toupper(str[i]); } printf("Uppercase string: %s", str); return 0; }
#include <stdio.h>
char to_upper(char c) {
if (c >= 'a' && c <= 'z')
return c - 32;
else
return c;
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++) {
str[i] = to_upper(str[i]);
}
printf("Uppercase string: %s", str);
return 0;
}Complexity: O(n) time, O(1) space
Time Complexity
The program loops through each character once, so time grows linearly with input size, making it O(n).
Space Complexity
The conversion is done in-place without extra arrays, so space complexity is O(1).
Which Approach is Fastest?
Manual ASCII subtraction and toupper() both run in O(n), but toupper() is optimized and safer for different locales.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual ASCII subtraction | O(n) | O(1) | Simple ASCII-only conversion |
| Using toupper() | O(n) | O(1) | Locale-aware and safer conversion |
| Function-based manual check | O(n) | O(1) | Readable and reusable code |
toupper() function for cleaner and locale-aware uppercase conversion.