In this tutorial, we will learn how to find capital letters in a string in the C programming language. The C library provides various character functions, such as isupper()
, which helps in identifying whether a character is a capital letter or not.
Step 1: Include necessary header files
To begin with, we need to include the necessary header files in the C program. We will require the stdio.h
and ctype.h
header files. The stdio.h
header file is used for input and output functions, and the ctype.h
header file provides the character functions.
1 2 |
#include <stdio.h> #include <ctype.h> |
Step 2: Read the string to be checked
Next, we will use the standard input function gets()
to read the string which we want to check for capital letters.
1 2 3 |
char str[100]; printf("Enter the string: "); gets(str); |
Step 3: Loop through the characters of the string
Now, we need to loop through the elements of the input string using the for loop. In this tutorial, we will use two variables i
for iterating through the string and count
for counting the capital letters.
1 2 3 4 |
int i, count = 0; for (i = 0; str[i]; i++) { // Check for capital letters } |
Step 4: Check for capital letters
Inside the loop, we will use the isupper()
function from the ctype.h
header file to check whether the given character is a capital letter or not. If the result is true (non-zero), we increment the count
variable.
1 2 3 |
if (isupper(str[i])) { count++; } |
Step 5: Display the count of capital letters
Finally, once the loop is completed, we will print the count of capital letters found in the given string using the printf()
function.
1 |
printf("\nNumber of capital letters in the given string: %d", count); |
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <stdio.h> #include <ctype.h> int main() { char str[100]; int i, count = 0; printf("Enter the string: "); gets(str); for (i = 0; str[i]; i++) { if (isupper(str[i])) { count++; } } printf("\nNumber of capital letters in the given string: %d", count); return 0; } |
Example output:
Enter the string: HeLLo WorLD! Number of capital letters in the given string: 5
Conclusion
In this tutorial, we learned how to find capital letters in a given string in C using the isupper()
function from the ctype.h
header file. This simple program makes it easy to count capital letters in any string.