In this tutorial our program will count the number of vowels, consonants, and digits using C programming language. I hope you will find my work useful.
My email address is jakerpomperada@gmail.com and jakerpomperada@yahoo.com
Program Listing
/* vowels_consonants.c
Author : Jake Rodriguez Pomperada, MAED-IT, MIT
www.jakerpomperada.com www.jakerpomperada.blogspot.com
jakerpomperada@gmail.com
Bacolod City, Negros Occidental Philippines
*/
#include <stdio.h>
#include <assert.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
typedef struct
{
int vowel_count;
int consonant_count;
int digit_count;
}Stat;
bool is_vowel(char ch)
{
const char vowels[] = "aeiou";
return strchr(vowels, tolower(ch)) != NULL;
}
bool is_consonant(char ch)
{
const char consonants[] = "bcdfghjklmnpqrstuvwxyz";
return strchr(consonants, tolower(ch)) != NULL;
}
void do_stats(const char* txt, size_t size, Stat *stat)
{
assert(txt != NULL && size > 1);
assert(stat != NULL);
const char *cp = txt;
while (size--)
{
if (is_vowel(*cp))
stat->vowel_count++;
else if (is_consonant(*cp))
stat->consonant_count++;
else if (isdigit(*cp))
stat->digit_count++;
cp++;
}
}
void print_stats(const Stat* stat)
{
assert(stat != NULL);
printf("\tStatistics:\n");
printf("\t===========\n");
printf("\t Vowels : %d\n", stat->vowel_count-1);
printf("\t Consonants: %d\n", stat->consonant_count);
printf("\t Digits : %d\n", stat->digit_count);
}
int main()
{
Stat stat = {0,0,0};
printf("\n\n");
printf("\tCount Vowels,Consonants, and Digits in C");
printf("\n\n");
const char input[] = "Jake Pomperada, 42 years old and 173 cm tall.";
printf("\t%s", input);
printf("\n\n");
do_stats(input, sizeof(input), &stat);
print_stats(&stat);
printf("\n\n");
system("pause");
}
No comments:
Post a Comment