LearnFrenzy
Sign in Take a free test

Pointers · Pointer Programs · Question 6

C program to count vowels and consonants using a pointer Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Count the vowels and consonants in a sentence by walking through it with a char pointer.

Solution
main.c
#include <stdio.h>
#include <ctype.h>

int main(void) {
    const char *s = "Pointers make C powerful";
    int vowels = 0, consonants = 0;

    for (const char *p = s; *p; p++) {
        char c = (char) tolower((unsigned char) *p);
        if (c >= 'a' && c <= 'z') {
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
                vowels++;
            else
                consonants++;
        }
    }
    printf("Vowels: %d\nConsonants: %d\n", vowels, consonants);
    return 0;
}

Output Verified by compiling and running

Vowels: 8
Consonants: 13

The loop runs until *p is the terminating zero. tolower() handles capital letters, and only letters are counted, so spaces are skipped.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Popular