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);
CodePudding user response:
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;
}
}
CodePudding user response:
Your function needs to know what is the size of the 2D char array.
size_t countVoweles(size_t lines, size_t chars, char inputArray[lines][chars])
{
size_t total = 0;
const char vowels[] = "aAeEiIoOuU";
for (size_t i = 0; i < lines; i )
{
for (size_t j = 0; inputArray[i][j]; j )
{
total = !!strchr(vowels, inputArray[i][j]);
}
}
return total;
}
int main(void)
{
char x[][256] = {
"<Compilation failed>",
"# For more information see the output window",
"# To open the output window, click or drag the \"Output\" icon at the bottom of this window",
};
printf("%zu\n", countVoweles(sizeof(x)/ sizeof(x[0]), sizeof(x[0]), x));
}