Explanation
The program converts a sentence entered by the user to lowercase using the ctype.h
library function tolower
.
Header
The code begins with including the standard input-output header file and the ctype header file using #include <stdio.h>
and #include <ctype.h>
.
Variable Declaration
The main()
function is defined, and a character array is declared:
char sentence[100];
: Array to hold the input sentence with a maximum length of 99 characters plus the null terminator.
Program Description
The program prints a description message for the user to understand its functionality.
User Input
The user is prompted to enter a sentence:
printf("Enter a sentence: ");
: Prompts the user to enter a sentence.fgets(sentence, sizeof(sentence), stdin);
: Reads the sentence including spaces and stores it in the arraysentence
.
Convert to Lowercase
The program converts the sentence to lowercase using the tolower
function:
for (int i = 0; sentence[i] != '\0'; i++)
: Loops through each character of the sentence until the null terminator is reached.sentence[i] = tolower(sentence[i]);
: Converts each character to lowercase using thetolower
function.
Output Result
The program prints the converted sentence:
printf("Lowercase: %s\n", sentence);
: Prints the sentence after converting it to lowercase.
Program End
The program ends with return 0;
to indicate successful execution.
Code
/*
* -----------------------------------------------------------
* Logic Building with Computer Programming (CSU1128)
* Instructor: Dr. Pankaj Vaidya | Author: Divya Mohan
*
* This code is a part of the educational initiative by dmj.one
* with aim of empowering and inspiring learners in the field of
* Computer Science and Engineering through the respective courses.
*
* (c) 2022, Divya Mohan for dmj.one. All rights reserved.
* -----------------------------------------------------------
*/
#include <stdio.h>
#include <ctype.h>
int main()
{
printf("\n\n Program to convert a sentence entered by the user to lowercase by using the external library ctype.h \n\n");
char sentence[100];
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin);
// Convert the sentence to lowercase
for (int i = 0; sentence[i] != '\0'; i++)
{
sentence[i] = tolower(sentence[i]);
}
printf("Lowercase: %s\n", sentence);
return 0;
}
Output
Program to convert a sentence entered by the user to lowercase by using the external library ctype.h
Enter a sentence: This IS a DeMo sentence.
lowercase: this is a demo sentence