Count the Number of Vowels in a String

This C program counts the number of vowels in a given string. The vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ (both uppercase and lowercase).

Program Structure and Explanation

The program follows these steps:

  • Define a function to count the vowels in the given string.
  • Prompt the user to enter a string.
  • Call the function and display the result.

Code:


#include <stdio.h>
#include <string.h>

// Function to count the number of vowels in a string
int countVowels(char *str) {
int count = 0;
char c;

// Iterate through the string character by character
for (int i = 0; str[i] != ‘\0’; i++) {
c = str[i];

// Convert to lowercase if the character is uppercase
if (c >= ‘A’ && c <= ‘Z’) {
c = c + ‘a’ – ‘A’;
}

// Check if the character is a vowel
if (c == ‘a’ || c == ‘e’ || c == ‘i’ || c == ‘o’ || c == ‘u’) {
count++;
}
}

return count;
}

int main() {
char str[100];

// Prompt the user to enter a string
printf(“Enter a string: “);
fgets(str, sizeof(str), stdin);

// Remove the newline character from the string
str[strcspn(str, “\n”)] = ‘\0’;

// Count the vowels in the string
int vowelCount = countVowels(str);

// Display the result
printf(“Number of vowels: %d\n”, vowelCount);

return 0;
}

Explanation:

  • The countVowels function takes a string as input and iterates through each character.
  • It converts any uppercase character to lowercase to simplify vowel checking.
  • The function checks if the character is a vowel (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) and increments the count if true.
  • In the main function, the user is prompted to enter a string. The fgets function is used to read the input string.
  • The newline character from the input is removed using strcspn.
  • The countVowels function is called, and the result is displayed.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)