Rewrite C Function: tolower

Last Updated : 10 July, 2022 · 2 min read

The standard C library offers a number of functions that allow users to modify character values. The tolower function is one of such functions, which we are going to discuss here. In this article, you can expect to:

Structure of tolower:

Declaration: int tolower(int c);

Return: unmodified integer value of parameter c or a sum of received parameter and 32 (c + 32).

Parameter list:
(int c) - an integer value to be modified, if it represents an uppercase character.

Header file: <ctype.h>.

1. So, what is tolower function?

The tolower function in C programming language modifies uppercase characters to lowercase ones. The uppercase characters in C programming language fall in the ASCII range from 65 to 90. To these values does the tolower function add 32. Which turns a character from uppercase to lowercase.

If you were to pass any other non-uppercase character to the tolower function, you would receive the exact same value back from this function. To see how to use this ctype.h library function, you can consider the code snippet below (example 1).

Example 1: Printing lowercase alphabet using tolower function.

# include <stdio.h>
# include <ctype.h>
int main ()
{
    
printf ( "Now you know the " );
    
for ( int i = 'A' ; i <= 'Z' ; i++)
    
{
        
printf ( "%c" , tolower(i));
    
}
    
return 0;
}
					

Possible output:

Now you know the abcdefghijklmnopqrstuvwxyz

2. And how to implement the tolower function in C?

Now, for an accurate implementation of the tolower function, you should make sure that your function returns appropriate values. If the received parameter is not an uppercase character, you should return the same integer value. Otherwise, you should add 32 to the received parameter and return the sum. Below you can find a way to write this in C programming language (example 2).

Example 2: Rewritten tolower function in C.

int our_tolower ( int c)
{
    
if (c >= 'A' && c <= 'Z' )
        
return (c + 32);
    
return (c);
}
					

Here, we define the our_tolower function that receives and returns integer values. The return value depends on the condition (on line 3). Given that this condition is true, it means that the received parameter can be implicitly (or explicitly) converted to an uppercase character. In which case, 32 is added (on line 4) and the sum is returned. If the condition is false, however, then the parameter value is equal to the return value.

3. Quiz of the tolower function

Quiz : Rewritten tolower function in C

1What does the tolower function NOT do?

2Which of the following ranges contain all the lowercase alphabet characters?

3What is the return value of tolower(69)?

quiz completed!

Congrats!

Feel free to share your achievement below!