Letters and Digits Total
Problem:
Write a C program that calculates the total number of letters and digits in a given string. The program should prompt the user to enter a string and then display the total number of letters and digits in that string.
Solution:
Here is an example C program that calculates the total number of letters and digits in a given string:
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int letters = 0, digits = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letters++;
} else if (isdigit(str[i])) {
digits++;
}
}
printf("Total letters: %d\n", letters);
printf("Total digits: %d\n", digits);
return 0;
}
Let's go through the code step by step:
We include the necessary header files:
stdio.h
for input/output operations andctype.h
for character classification functions.We declare the variables
str
to store the input string,letters
to count the number of letters, anddigits
to count the number of digits.We prompt the user to enter a string using the
printf
function and read the input using thefgets
function. Thefgets
function reads a line of text from the standard input (keyboard) and stores it in thestr
variable.We use a
for
loop to iterate over each character in the string. The loop continues until the null character ('\0'
) is encountered, indicating the end of the string.Inside the loop, we use the
isalpha
function from thectype.h
library to check if the current character is a letter. If it is, we increment theletters
variable.We also use the
isdigit
function to check if the current character is a digit. If it is, we increment thedigits
variable.After the loop, we print the total number of letters and digits using the
printf
function.Finally, we return
0
to indicate successful program execution.
This program counts both uppercase and lowercase letters as well as decimal digits (0-9). It ignores any other characters, such as punctuation or whitespace.
I hope this helps! Let me know if you have any further questions.