C program to convert uppercase string to lowercase

Write a C program to convert uppercase string to lowercase using for loop. How to convert uppercase string to lowercase without using inbuilt library function strlwr().

Write a C program to convert uppercase string to lowercase using inbuilt string library function strlwr(). How to use strlwr library function in C programming.

Example :
Input string: I love PROGRAMMING!
Output string: i love programming!

Required knowledge

Basic C programming, Loop, String

Logic to convert uppercase string to lowercase

Internally characters in C are represented as an integer value known as ASCII value. Which means if we write a or any other character it is translated into a numeric value in our case it is 97 as ASCII value of a = 97.

Here what we need to do is first we need to check whether the given character is upper case alphabet or not. If it is uppercase alphabet just add 32 to it which will result in lowercase alphabet (Since ASCII value of A=65, a=97 their difference is 97-65 = 32).
Algorithm to convert uppercase to lowercase
%%Input : text {Array of characters / String}
         N {Size of the String}
Begin:
    For i ← 0 to N do
        If (text[i] >= 'A' and text[i] <= 'Z') then
            text[i] ← text[i] + 32;
        End if
    End for
End


Program to convert uppercase string to lowercase

/**
 * C program to convert uppercase to lowercase string without using inbuilt library function
 */

#include <stdio.h>

#define MAX_SIZE 100 //Maximum size of the string

int main()
{
    char string[MAX_SIZE];
    int i;
 
    /* Reads string from user */
    printf("Enter any string: ");
    gets(string);


    //Runs a loop till last character of string
    for(i=0; string[i]!='\0'; i++)
    {
        if(string[i]>='A' && string[i]<='Z')
        {
            string[i] = string[i] + 32;
        }
    }

    printf("Lower case string: %s\n", string);

    return 0;
}


Note: You can also use inbuilt library function strlwr() to convert strings to lowercase. It is defined in string.h header file.


Program to convert uppercase string to lowercase using strlwr()

/**
 * C program to convert uppercase string to lowercase using strlwr() string function
 */

#include <stdio.h>
#include <string.h>

#define MAX_SIZE 100 //Maximum size of the string

int main()
{
    char string[MAX_SIZE];

    /* Reads string from user */
    printf("Enter any string: ");
    gets(string);

    strlwr(string); //Converts to lowercase

    printf("Lowercase string: %s\n", string);

    return 0;
}


Output
Enter any string: I love PROGRAMMING!
Lowercase string : i love programming!


Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment