C - Converting uppercase letter to lowercase letter

Introduction

A char value may be expressed either as an integer or as a character between quotes, such as 'A'.

When type char is signed, values can be from -128 to +127.

When char is an unsigned type, values can be from 0 to 255.

You can compare values of type char:

'Z' >= 'A'      'Q' <= 'P'      'B' <= 'b'      'B' != 66

ASCII codes for lowercase letters are 32 higher than their uppercase equivalents.

The following example will convert any uppercase letter that is entered to lowercase:

Demo

#include <stdio.h>

int main(void)
{
      char letter = 0;                          // Stores a character

      printf("Enter an uppercase letter:");     // Prompt for input
      scanf("%c", &letter);                     // Read a character

      // Check whether the input is uppercase
      if(letter >= 'A'){                         // Is it A or greater?
            if(letter <= 'Z')                       // and is it Z or lower?
            {                                       // It is uppercase
              letter = letter - 'A' + 'a';          // Convert from upper- to lowercase
              printf("You entered an uppercase %c\n", letter);
            }/*ww w .j av a  2  s  . c  om*/
      }else{// It is not an uppercase letter
          printf("Try using the shift key! I want a capital letter.\n");
      }                                    
          
      return 0;
}

Result

if a capital letter is entered, the character in letter must be between 'A' and 'Z', so the next if checks whether the character is greater than or equal to 'A':

if(letter >= 'A')                         // Is it A or greater?

if the expression is true, you continue with the nested if that tests whether letter is less than or equal to 'Z':

if(letter <= 'Z')                         // and is it Z or lower?

if this expression is true, you convert the character to lowercase and output a message by executing the block of statements following the if:

{                                         // It is uppercase
  letter = letter - 'A' + 'a';            // Convert from upper- to lowercase
  printf("You entered an uppercase %c\n", letter);
}

Related Topic