0

Code: //Program to find no of vowels

#include<stdio.h>
int main()
{
    int count;char letter;int vowel=0;
    for(count=0;count<10;count++)
    {
        letter=getchar();
        switch(letter)
        {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':vowel++;
        }printf("Count:%d",count);
    }
    printf("NO of vowels is %d\n",vowel);

return 0;
}

Output: a a s d f NO of vowels is 2

The program reads only 5 characters and then displays the expected output. I tried printing the value of 'count' and by the end of loop, it incremented to 10. But,I am not able to read the number of characters(10) equivalent to my for loop condition. Please help.

vim
  • 84
  • 1
  • 2
  • 9

3 Answers3

1

Space ' ' is also a character. getchar reads a character at a time and hence reads ' ' too. Remove spaces from the input.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

I'm surprised you didn't notice from the printf("Count: %d\n"); line that the count increments by two for each letter of input. The getChar function gets all of the characters from the input text, including spaces and newlines. The simplest way to make your program behave as you expect is to increase the maximum count to 20:

for(count = 0; count < 20; count++)
{
    letter = getchar();
    // ...

Alternatives include using scanf and checking for reaching the end of text input, but your implementation is much safer.

Austin Mullins
  • 7,307
  • 2
  • 33
  • 48
  • 1
    Maybe it is not good to use 20 instead of 10? Because new line can be in two chars and then one should use 30 when read from standard input. Better to use something like getch, or change terminal behaviors – Ivan Ivanov Jul 18 '14 at 17:51
  • 1
    Newline is one char, `'\n'`. But the file could have other whitespace. Instead of guessing a number like 20 or 30, only increment the counter when you read a non-whitespace. – M.M Jul 19 '14 at 00:17
0
#include <stdio.h>
#include <ctype.h>

int main(){
    int count=0, vowel=0;
    char letter;
    while(count < 10){
        letter=getchar();
        if(isgraph(letter)){
            switch(tolower(letter)) {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':vowel++;
            }
            ++count;//Counting only the case of the display characters that are not blank
        }
    }
    printf("NO of vowels is %d\n",vowel);

    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70