C Program to Convert a String to Uppercase and Lowercase
Write a C program to convert a string to uppercase and lowercase.
- Reads a string from input one character at a time until newline (\n) is encountered.
- Stores the null terminator (\0) to properly mark the end of the string.
- Converts and prints each lowercase letter to uppercase by subtracting 32 from its ASCII value.
- Converts and prints each uppercase letter to lowercase by adding 32 to its ASCII value.
Example : pgm.c
#include <stdio.h> int main() { char str[100]; int i = 0; printf("Enter a string: "); while ((str[i] = getchar()) != '\n') { i++; } str[i] = '\0'; // Convert to Uppercase printf("Uppercase: "); for (i = 0; str[i] != '\0'; i++) { if (str[i] >= 'a' && str[i] <= 'z') { printf("%c", str[i] - 32); // 'a' to 'A' = ASCII -32 } else { printf("%c", str[i]); } } // Convert to Lowercase printf("\nLowercase: "); for (i = 0; str[i] != '\0'; i++) { if (str[i] >= 'A' && str[i] <= 'Z') { printf("%c", str[i] + 32); // 'A' to 'a' = ASCII +32 } else { printf("%c", str[i]); } } printf("\n"); return 0; }
Output :
Enter a string: Hello World
Uppercase: HELLO WORLD
Lowercase: hello world
Uppercase: HELLO WORLD
Lowercase: hello world