Search code examples
cmultidimensional-arraycharnested-loopsc-strings

Count vowels in each of the strings using two dimensional array


I need to write a program where the user enters the number of strings and the program counts the number of vowels in each string and prints the total number of vowels. The following code works without two dimensional array

int countVoweles(char inputArray[])
{
    int total = 0;
    char vowels[] = "aAeEiIoOuU";
    for (int i = 0; inputArray[i]; i++)
    {
        for (int j = 0; vowels[j]; j++)
        {
            if (inputArray[i] == vowels[j])
            {
                total++;
            }
        }
    }
    return total;
}

However, the following code does not work with two dimensional array. It prints vowels only from the first string.

How can I print vowels from all strings entered?

char name[3][10];
    int total = 0;
    char vowels[] = "aAeEiIoOuU";
    printf("Enter your string :");
    for (int i = 0; i < 3; i++)
    {
        gets(name[i]);
    }
    printf("The total number of vowels are :\n");
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; name[i][j]; j++)
        {
            if (name[i][j] == vowels[i])
            {
                total++;
            }
        }
    }
    printf("%d", total);

Solution

  • For starters pay attention to that the function gets is unsafe and is not supported by the C Standard. Instead use the standard function fgets as for example

    fgets( name[i], sizeof( name[i] ), stdin );
    

    As for your problem then you need one more loop to traverse the array with vowels for a given character in strings of the array name.

    For example

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; name[i][j]; j++)
        {
            int k = 0;
            while ( vowels[k] && name[i][j] != vowels[k] ) ++k;
            if ( vowels[k] )
            {
                total++;
            }
        }
    }
    

    Another approach is to use your already written function like

    for (int i = 0; i < 3; i++)
    {
        total += countVoweles( name[i] );
    }
    

    Instead of using a loop to traverse the array vowels you could use standard C function strchr declared in the header <string.h> as for example

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; name[i][j]; j++)
        {
            total += strchr( vowels, name[i][j] ) != NULL;
        }
    }