C Program to Convert String to Uppercase
if(str[i] >= 'a' && str[i] <= 'z') str[i] = str[i] - 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("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 not between 'a' and 'z', so no change
Check second character 'e'
'e' is lowercase, convert to 'E' by subtracting 32
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 | Character Before | Is Lowercase? | Character After |
|---|---|---|---|
| 0 | H | No | H |
| 1 | e | Yes | E |
| 2 | l | Yes | L |
| 3 | l | Yes | L |
| 4 | o | Yes | O |
Why This Works
Step 1: Check each character
The program looks at each character in the string one by one using a loop.
Step 2: Identify lowercase letters
It uses if(str[i] >= 'a' && str[i] <= 'z') to find lowercase letters.
Step 3: Convert to uppercase
It converts lowercase letters to uppercase by subtracting 32 from their ASCII value, because uppercase letters are 32 positions before lowercase in ASCII.
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] = toupper(str[i]); i++; } printf("Uppercase string: %s", str); return 0; }
#include <stdio.h> #define DIFF ('a' - 'A') int main() { char str[100]; int i = 0; printf("Enter a string: "); fgets(str, sizeof(str), stdin); while (str[i]) { if (str[i] >= 'a' && str[i] <= 'z') { str[i] = str[i] - DIFF; } 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 string length.
Space Complexity
The conversion happens in place, so no extra space is needed besides the input string.
Which Approach is Fastest?
Using toupper() is usually optimized and clearer, but manual ASCII subtraction is also fast and simple.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual ASCII check and subtract | O(n) | O(1) | Simple programs without extra includes |
| Using toupper() function | O(n) | O(1) | Cleaner code and handling locale |
| Using ASCII difference constant | O(n) | O(1) | Readable manual conversion |
toupper() function for cleaner and safer uppercase conversion.