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:

  1. We include the necessary header files: stdio.h for input/output operations and ctype.h for character classification functions.

  2. We declare the variables str to store the input string, letters to count the number of letters, and digits to count the number of digits.

  3. We prompt the user to enter a string using the printf function and read the input using the fgets function. The fgets function reads a line of text from the standard input (keyboard) and stores it in the str variable.

  4. 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.

  5. Inside the loop, we use the isalpha function from the ctype.h library to check if the current character is a letter. If it is, we increment the letters variable.

  6. We also use the isdigit function to check if the current character is a digit. If it is, we increment the digits variable.

  7. After the loop, we print the total number of letters and digits using the printf function.

  8. 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.