C Program to Count the Number of Vowels, Consonants, Digits, and Spaces
Write a C program that counts vowels, consonants, digits, and spaces in a given string:
- Reads the input string one character at a time until a newline (\n) is encountered.
- Checks and counts if the character is a vowel (a, e, i, o, u - both cases).
- Checks and counts digits (characters between '0' and '9') and spaces (' ').
- Counts consonants by checking if the character is an alphabet but not a vowel.
Example : pgm.c
#include <stdio.h> int main() { char str[200]; int vowels = 0, consonants = 0, digits = 0, spaces = 0; int i = 0; char ch; printf("Enter a string: "); // Read character by character until newline while ((ch = getchar()) != '\n') { str[i] = ch; // Check for vowels if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') { vowels++; } // Check for digits else if (ch >= '0' && ch <= '9') { digits++; } // Check for spaces else if (ch == ' ') { spaces++; } // Check for consonants (alphabet characters excluding vowels) else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { consonants++; } i++; } printf("Vowels: %d\n", vowels); printf("Consonants: %d\n", consonants); printf("Digits: %d\n", digits); printf("Spaces: %d\n", spaces); return 0; }
Output :
Enter a string: Welcome 2025
Vowels: 3
Consonants: 4
Digits: 4
Spaces: 1
Vowels: 3
Consonants: 4
Digits: 4
Spaces: 1