Count consonants in the sentence

Asked

Viewed 1,648 times

3

The program must count the number of consonants in the sentence.

If only one word is typed it counts right, but if I give space, ie, write a sentence it does not count right.

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

int main()
{
   char vogais[]="aeiouAEIOU",frase[30];
   int vogal=0,i,j,tamanho,consoante;

   printf("Digite uma frase:");
   scanf("%[^\n]",frase);
   tamanho=strlen(frase);
   for(i=0;i<10;i++){

    for(j=0;j<tamanho;j++){
        if(vogais[i]==frase[j] || frase[j]==' '){
            vogal++;
        }
    }
   }
   consoante=tamanho-vogal;

   printf("A quantidade de consoantes na frase:%s:%d",frase,consoante);

    return 0;
}
  • Note that the way you did the sentence is swept several times (the for(i=0;i<10;i++){), and therefore any spaces are counted multiple times.

4 answers

2


It’s no use just considering space, as done in your answer, because if a character like @, % or !, it will be counted as consonant. For example, if the typed text is "a b c,!&defXYZ @ ABC", your code says there are 13 consonants (see), because you only considered that the spaces are not consonants, but the characters ,, !, & and @ were considered in the count.

What you need to do is check if the character is actually a letter (and in the code below I’m only considering not accented letters of our alphabet), and then discard the vowels:

int main(void) {
    char frase[30];
    int consoantes = 0;

    printf("Digite uma frase:");
    scanf("%[^\n]",frase);

    for (int i = 0; frase[i] != '\0'; i++){
        char c = frase[i];
        // se for maiúscula, converte para minúscula (excluí o "A", porque nesse caso nem precisa contabilizar)
        if ('B' <= c && c <= 'Z') c += 32;
        if ('b' <= c && c <= 'z') { // só testo se estiver neste intervalo
            switch(c) { // como já deixei o "a" de fora, não preciso mais testar aqui
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                    break; // se for vogal, não faz nada
                default: // é consoante
                    consoantes++;
            }
        }
    }

    printf("A quantidade de consoantes na frase '%s' é %d\n", frase, consoantes);
    return 0;
}

Now yes it correctly says that the string "a b c,!&defXYZ @ ABC" has 9 consonants, see.

Notice that first I check if the char is uppercase, and if so, I convert it to lowercase (just to facilitate the comparison that follows). To better understand how this works, give a read here. The detail is I’ve left the letter "a" out, so it’s one less letter to compare on switch.

Finally, when the code arrives in the block switch, at that point I’m sure the char is a lowercase letter from "b" to "z". So I just increment the counter if it’s not a vowel (and by leaving the letter "a" out and converting before it to lowercase makes the switch have fewer options to test, leaving the code more succinct - otherwise I would have to put 10 options case: the 5 uppercase and lowercase vowels).

This is much simpler - and correct - than counting the number of vowels and counting the space as if it were a vowel (because it only works if the string has only letters and spaces, any other character is erroneously counted as a consonant).

2

You can combine the function strchr() of the standard library string.h with the function tolower() of the standard library ctypes.h to simplify your algorithm.

The function strchr() traverse a string in search of the specified character and return NULL if the character is not contained within this string.

The function tolower() converts a letter/character to lowercase.

See how your show would look:

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

int main(void)
{
    char frase[100];
    int consoantes = 0;
    char * p = frase;

    printf("Digite uma frase: ");
    scanf("%[^\n]",frase);

    while(*p)
        if(strchr("bcdfghjklmnpqrstvwxyz", tolower(*p++)))
            consoantes++;

    printf("A quantidade de consoantes na frase '%s' é %d\n", frase, consoantes);
    return 0;
}

Testing:

Digite uma frase: O rato roeu a roupa do rei de Roma.                                    
A quantidade de consoantes na frase 'O rato roeu a roupa do rei de Roma.' é 10

See working on Repl.it

You could even implement a function solely responsible for counting consonants in a string, enabling its reusability:

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

int contar_consoantes(const char * s)
{
    int n = 0;
    while(*s)
        if(strchr("bcdfghjklmnpqrstvwxyz", tolower(*s++)))
            n++;
    return n;
}

int main(void)
{
    char frase[100];
    printf("Digite uma frase: ");
    scanf("%[^\n]",frase);
    printf("A quantidade de consoantes na frase '%s' é %d\n", frase, contar_consoantes(frase));
    return 0;
}

See working on Repl.it

And finally, a complete and simplified example:

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

#define eh_consoante(letra) (strchr("bcdfghjklmnpqrstvwxyz", tolower(letra))!=NULL)
#define eh_vogal(letra) (strchr("aeiou", tolower(letra))!=NULL)

int contar_consoantes(const char * frase)
{
    int n = 0;
    while(*frase)
        if(eh_consoante(*frase++))
            n++;
    return n;
}

int contar_vogais(const char * frase)
{
    int n = 0;
    while(*frase)
        if(eh_vogal(*frase++))
            n++;
    return n;
}

int main(void)
{
    char frase[100];

    printf("Digite uma frase: ");
    scanf("%[^\n]",frase);

    printf("Consoantes: %d\n", contar_consoantes(frase));
    printf("Vogais: %d\n", contar_vogais(frase));

    return 0;
}

See working on Repl.it

0

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

int main()
{
   char consoantes[]="bcdfghjklmnpqrstwvxyzç",frase[30];
   int i,j,tamanho,consoante=0;

   printf("Digite uma frase:");

   scanf("%[^\n]",frase);
   tamanho=strlen(frase);
   tolower(frase);

   for(i=0;i<19;i++){
    for(j=0;j<tamanho;j++){
        if(frase[j]==consoantes[i]){
            consoante++;
        }
    }
   }


   printf("A quantidade de consoantes na frase:%s:%d",frase,consoante);












    return 0;
}

0

I decided, I wasn’t paying attention was that the space counted as character,and that the size of the string increased with the space key.

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

int main()
{
   char vogais[]="aeiouAEIOU",frase[30];
   int vogal=0,i,j,tamanho,consoante;

   printf("Digite uma frase:");
   scanf("%[^\n]",frase);
   tamanho=strlen(frase);
   for(i=0;i<tamanho;i++){
    if(frase[i]==' '){
        vogal++;
    }
   }
   for(i=0;i<10;i++){

    for(j=0;j<tamanho;j++){
        if(vogais[i]==frase[j]){
            vogal++;
        }
    }
   }
   consoante=tamanho-vogal;

   printf("A quantidade de consoantes na frase:%s:%d",frase,consoante);












    return 0;
}
  • It’s not right yet. If you have other characters in the sentence, like ,, ., @, !, among others, the count goes wrong, see. Placed an answer which also works for these cases :-)

  • Thanks for the suggestions,totally forgot the other characters,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.