Home > Software design >  Why this approach for count vowels in a string is not working?
Why this approach for count vowels in a string is not working?

Time:05-10

#include<stdio.h>
int countVowels(char str[]);

int main(){
  char str[100]="hello world";
  printf("%d",countVowels(str));
}

// **make this function for vowel count**
int countVowels(char str[]){
     
  // I have made a character array for storing vowels
  char vowels[]="aeiou";
  int count=0;

  // loop for counting the vowels

  // for traversing the str array
  for(int i=0;str[i]!='\0';i  ){ 

    // for traversing the vowels array
    for(int j=0;vowels[j]!='\0';j  ){ 
  
      // comparison of every letter of str with vowels
      if(str[i]==vowels[j]){
        count  ;
      }
    }
    return count;
  }
}

CodePudding user response:

Your return count is inside your for loop. It's really worth the time to make sure you indent your code correctly.

int countVowels(char str[]){
     
  // I have made a character array for storing vowels
  char vowels[]="aeiou";
  int count=0;

  // loop for counting the vowels

  // for traversing the str array
  for(int i=0;str[i]!='\0';i  ){ 

    // for traversing the vowels array
    for(int j=0;vowels[j]!='\0';j  ){ 
  
      // comparison of every letter of str with vowels
      if(str[i]==vowels[j]){
        count  ;
      }
    }
  }
  return count;
}

CodePudding user response:

Your return count is in the wrong place, something that may have been clearer had you formatted your code a bit better :-)

But now that that's been done, it should be a little clearer. You are returning the count inside the outer for loop meaning you will have processed only the first character of the string.

This code should help illustrate a more correct way to do it:

#include<stdio.h>

int countVowels(char str[]){
    static const char vowels[] = "aeiou";
    int count = 0;

    for(int i = 0; str[i] != '\0'; i  ) {
        for(int j = 0; vowels[j] != '\0'; j  ) {
            if(str[i] == vowels[j]) {
                count  ;
            }
        }
    }
    return count;
}

int main(){
    char str[] = "hello world";
    printf("%d\n", countVowels(str));
}
  • Related