Introduction
Converting a string to uppercase involves changing all the lowercase characters in the string to their corresponding uppercase characters. This guide will show you how to write a C program to convert a string to uppercase.
Problem Statement
Create a C program that:
- Takes a string as input from the user.
- Converts all lowercase characters in the string to uppercase.
- Displays the converted string.
Example:
- Input: String = "Hello, World!"
- Output: Uppercase String = "HELLO, WORLD!"
Solution Steps
- Include the Standard Input-Output and Character Handling Libraries: Use
#include <stdio.h>for standard input-output functions and#include <ctype.h>for character handling functions. - Write the Main Function: Define the
mainfunction, which is the entry point of every C program. - Declare Variables: Declare a variable to store the input string.
- Input the String: Use
getsorscanfto take input from the user for the string. - Convert the String to Uppercase: Use a loop to iterate through each character of the string and convert it to uppercase using the
toupperfunction fromctype.h. - Display the Uppercase String: Use
printfto display the converted string.
C Program to Convert String to Uppercase
#include <stdio.h>
#include <ctype.h>
int main() {
// Step 1: Declare a variable to hold the input string
char str[100];
int i;
// Step 2: Prompt the user to enter a string
printf("Enter a string: ");
gets(str); // Using gets to read the string including spaces
// Step 3: Convert the string to uppercase
for (i = 0; str[i] != '\0'; i++) {
str[i] = toupper(str[i]);
}
// Step 4: Display the uppercase string
printf("Uppercase string: %s\n", str);
return 0; // Step 5: Return 0 to indicate successful execution
}
Explanation
Step 1: Declare Variables
- The variable
stris declared to store the input string. The variableiis used as a loop counter.
Step 2: Input the String
- The program prompts the user to enter a string using
printf. Thegetsfunction is used to read the string, allowing it to include spaces.
Step 3: Convert the String to Uppercase
- The program uses a
forloop to iterate through each character of the string:- The
toupperfunction from thectype.hlibrary converts each character to its uppercase equivalent if it is a lowercase letter.
- The
Step 4: Display the Uppercase String
- After converting the string to uppercase, the program displays the converted string using the
printffunction.
Step 5: Return 0
- The
return 0;statement indicates that the program executed successfully.
Output Example
Example 1:
Enter a string: Hello, World!
Uppercase string: HELLO, WORLD!
Example 2:
Enter a string: C Programming is fun!
Uppercase string: C PROGRAMMING IS FUN!
Conclusion
This C program demonstrates how to convert a string to uppercase by iterating through each character and using the toupper function. It covers basic concepts such as string manipulation, loops, and character handling, making it a useful example for beginners learning C programming.