Here we will see two programs for lowercase to uppercase conversion. First program converts lowercase character to uppercase and the second program converts lowercase string to uppercase string.
Example 1: Program to convert Lowercase character to uppercase
ASCII value of lowercase char a to z ranges from 97 to 122
ASCII value of uppercase char A to Z ranges from 65 to 92
For conversion we are subtracting 32 from the ASCII value of input char.
#include <iostream> using namespace std; int main() { char ch; cout<<"Enter a character in lowercase: "; cin>>ch; ch=ch-32; cout<<"Entered character in uppercase: "<<ch; return 0; }
Output:
Example 2: Program to convert Lowercase String to Uppercase String
In this program user is asked to enter a string and then the program converts that input string into an uppercase string.
Logic used here: Looping through all the characters of the input string and checking whether the character lies in the ASCII range 97 to 122 (all the lowercase chars lies in this range). If the character is found to be in this range then the program converts that character into an uppercase char by subtracting 32 from the ASCII value.
#include <iostream> #include <string> using namespace std; int main() { char s[30]; int i; //display a message to user to enter the string cout<<"Enter the String in lowercase: "; //storing the string into the char array cin>>s; /* running the loop from 0 to the length of the string * to convert each individual char of string to uppercase * by subtracting 32 from the ASCII value of each char */ for(i=0;i<=strlen(s);i++) { /* Here we are performing a check so that only lowercase * characters gets converted into uppercase. * ASCII value of a to z(lowercase chars) ranges from 97 to 122 */ if(s[i]>=97 && s[i]<=122) { s[i]=s[i]-32; } } cout<<"The entered string in uppercase: "<<s; return 0; }
Output:
Leave a Reply