Home > Mobile >  c: How can I print only the highest numbered vowel?
c: How can I print only the highest numbered vowel?

Time:08-11

I just want to print highest numbered vowel.
For ex: the cat is the cat. In this sentence,

the vowel a is repeated 2 times  
the vowel e is repeated 2 times  
the vowel i is repeated 1 times  
the vowel o is repeated 0 times  
the vowel u is repeated 0 times  

I just want to see a and e in the console.

Here is the code.

void vowel(char st2[]){

   char vow[]="aeiou"; //vowel
   int i=0,j=0,count=0;
   while(vow[i]!='\0'){ //loop until sentence ends
       count=0;
       for(j=0;j<strlen(st2);j  ) 
       {
           if(st2[j]==vow[i]){ //increment the counter by one if one letter in the sentence is equal to the vowels
               count  ;                   
           }
       }
      
       printf("the vowel %c is repeated %d times\n",vow[i],count);
       i  ;
   }
}

CodePudding user response:

Here, in this version, we count how many occurrences there are of a vowel, and only print the highest one.

void vowel(char st2[]){

   char vow[]="aeiou"; //vowel
   int length = strlen(st2);
   int counts[] = {0,0,0,0,0};
   int i=0,j=0,count=0;
   while(vow[i]!='\0'){ //loop until sentence ends
       count=0;
       for(j=0;j<length;j  ) 
       {
           if(st2[j]==vow[i]){ //increment the counter by one if one letter in the sentence is equal to the vowels
               count  ; 
               counts[i] = count;                  
           }
       }
       i  ;
   }
   int highest = 0;
   for(int i = 0; i < 5; i  ){
    if(counts[i] > highest){
        highest = counts[i];
    }
   }
   for(int i = 0; i< 5; i  ){
    if(counts[i] == highest){
        printf("the vowel %c is repeated %d times\n",vow[i],highest);
    }
   }
}

CodePudding user response:

The elegance of C is that one can obtain functionality with very little code.

int main() {
    char *str = "The quick brown fox jumps over the lazy dog";
    char which = 'a'; // default
    int maxCnt = 0;

    for( char *pv = "aeiou"; *pv; pv   ) {
        int cnt = 0;
        for( char *cp = str; *cp; cp   )
            cnt  = ( *cp == *pv );

        if( cnt > maxCnt ) {
            maxCnt = cnt;
            which = *pv;
        }
    }
    if( maxCnt )
        printf( "Vowel '%c' occurs %d times.\n", which, maxCnt );
    else
        printf( "NO vowels found in '%s'.\n", str );

    return 0;
}
  •  Tags:  
  • c
  • Related