C program to print vowels in a string

C program to print vowels in a string and their location. We need to find all vowels (lower case and upper case) in a given string and its location.

For example,

Input: Hello world

Output:

Vowel: e at location: 1
Vowel: o at location: 4
Vowel: o at location: 7

Solution to find vowels in String

Solution is very simple, we can store string into a char array. Retrieve each char using a for loop and compare them with all vowels i.e. a, e, i, o, u, A, E, I, O, U . If character is matching, we can print the locating and character.

NOTE:

To read the input string e.g. Hello World, in scanf function, we need to use the expression scanf(“%[^\n]s”, str); – notice the [^\n]. It will read the string including space. If we use simple like scanf(“%s”, str); to read string, then only first word e.g. in hello world, only hello will be read by scanf.

C program to print vowels in a string and their locations.

/*
* C program to print vowels in a string
*/

#include <stdio.h>

int main(){

	int index, str_length;

	//Create char buffer to store string
	char str[50];

	printf("\nEnter string: ");

	//Note that only %s in scanf read first word and
	//not able to handle space in string

	//So, if we use [^\n] in it will handle space also.
	scanf("%[^\n]s", str);

	//Get length of the entered string
	str_length = strlen(str);

	//Read each character from a string using index
	//and for loop till 1 less than string lenght
	//as we are starting from 0

	//Every time you read character, compare each char with
	// all vowels. If true then print index(location of char)
	//and charater( vowels)
	for(index = 0; index < str_length; index++)
	{
		if(str[index] == 'a' || str[index] == 'e' ||
			str[index] == 'i' || str[index] == 'o' || 
			str[index] == 'u' || str[index] == 'A' ||
			str[index] == 'E' || str[index] == 'I' ||
			str[index] == 'O' || str[index] == 'U')
		{
			//Display vowel found in string and its location
			printf("Vowel: %c at location: %d\n",str[index], index );
		}
	}

	return 0;
}

Related Posts