Contact Learn C
Copy

Program 84:To convert upper to lower and vice versa

Program 84:
 
#include<stdio.h>
#include<string.h>
main()
{
    int i;
    char str1[100],str2[100]={0};
    printf("Enter a sentence to convert upper to lower and vice versa\n");
    gets(str1);
for(i=0;i<strlen(str1);i++)
{
    if(str1[i]>'a'&&str1[i]<'z')
    {
        str2[i]=(char)str1[i]-32;
    }
    else if(str1[i]>'A'&&str1[i]<'Z')
    {
        str2[i]=(char)str1[i]+32;
    }
    else
    {
        str2[i]=str1[i];
    }
}
printf("The converted sentence is %s\n",str2);
}
Explanation:
Logic of the program: If the entered string is HellO then

H is added with 32 to get 'h'(as 'H' ascii value is 72 so if it is added with 32 then 72+32 is 104 which is 'h') and is stored in another variable.

'e' is subtracted with 32 to get 'E'(as 'e' ascii value is 101 so if it is subtracted with 32 then 101-32 is 69 which is 'E').

So if it is capital letter,it is added with 32.If it is small letter it is subtracted with 32.

  1. This program starts with initializing :
    • str1[100] → To store string with length of 100 which means it can store 100 letters given by user
    • str2[100] → To store converted string
    • i →Used as helping variable
  2. printf("Enter a sentence to convert upper to lower and vice versa\n");
        gets(str1);
    To take string from user 
  3. for(i=0;i<strlen(str1);i++)
    {
        if(str1[i]>'a'&&str1[i]<'z')
        {
            str2[i]=(char)str1[i]-32;
        }
        else if(str1[i]>'A'&&str1[i]<'Z')
        {
            str2[i]=(char)str1[i]+32;
        }
        else
        {
            str2[i]=str1[i];
        }
    }
    Converts 'H' to h by adding 32 to 'H'.Similarly if letter is 'e' then it is subtracted with 32 to get 'E' .Each time it converts it will store character by character in another variable (say str2)
  4. Finally str2 is printed.
printf("The converted sentence is %s\n",str2);

Output:

To convert upper to lower and vice versa
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide