Here we will see two programs for uppercase to lowercase conversion in C++. In the first program we will convert the input uppercase character into lowercase and in the second program we will convert a uppercase string into lowercase.
Example 1: Program to convert Uppercase char to lowercase char
This program converts the input uppercase character into a lowercase character. The logic that we are using here is that the ASCII value difference between uppercase and lowercase char is 32. All the lowercase characters have +32 ASCII value corresponding to their uppercase counter parts. For example ASCII value of char ‘B’ is 66 and the ASCII value of char ‘b’ is 98.
User is asked to enter the uppercase char and then we are adding the 32 value to it to convert it into a lowercase character.
#include <iostream> using namespace std; int main() { char ch; cout<<"Enter a character in uppercase: "; cin>>ch; //converting the uppercase char to lowercase by adding 32 //to the ASCII value of the input character ch=ch+32; cout<<"Entered character in lowercase: "<<ch; return 0; }
Output:
Example 2: Program to convert Uppercase String to Lowercase String
In this program user is asked to enter the string(string can be in all uppercase or mixed cases) and then the program converts the String into all lowercase string.
#include <iostream> #include <string> using namespace std; int main() { char s[20]; int i; //display a message to user to enter the string cout<<"Enter the String in uppercase: "; //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 lowercase * by adding 32 to the ASCII value of each char */ for(i=0;i<=strlen(s);i++) { /* Here we are performing a check so that only those * characters gets converted into lowercase that are * in uppercase. * ASCII value of A to Z(uppercase chars) ranges from 65 to 92 */ if(s[i]>=65 && s[i]<=92) { s[i]=s[i]+32; } } cout<<"The entered string in lowercase: "<<s; return 0; }
Output:
Leave a Reply