C program to find the first vowel in a user input string

C program to find the first vowel in a string :

In this C programming tutorial, we will learn how to find first vowel in a string using C language. For example, for the string Hello World !!, the first vowel is e.This character should be print out by the program. The user will enter one string, our program will read it and store it in an array. Let’s take a look at the program first :

C program :

#include

//7
int isVowel(char c){
	//8
	switch(c){
		case 'a':
		case 'e':
		case 'i':
		case 'o':
		case 'u':
		case 'A':
		case 'E':
		case 'I':
		case 'O':
		case 'U':
			return 1;
		default :
			return 0;
	}
}

int main()
{
	//1
	char inputString[100];
	int i;
	int flag = 0;

	//2
	printf("Enter your string : ");
	fgets(inputString, 100, stdin);

	//3
	for(i = 0; inputString[i] != '\n' ;i++){
		//4
		if(isVowel(inputString[i])){
			//5
			printf("First vowel is : %c \n",inputString[i]);
			flag = 1;
			break;
		}
	}

	//6
	if(!flag){
		printf("No vowel found.\n");
	} 

	
}

Explanation :

The commented numbers in the above program denote the step number below :

1. Create one char array (inputString) to store the user input string. One integer i to use in the for loop and one integer flag to detect if any vowel is found or not. flag = 0 means no vowel found. If any vowel detects, we will change the value of flag to 1.
2. Ask the user to enter one string. Read it and store it in the variable inputString
3. Run one for loop to read each character of the input string one by one. This loop will run till a new line found or string-end reached.
4. Check if the current character is vowel or not using the function isVowel.
5. If any vowel character found, print it , change the value of flag to 1 and exit from the loop using break statement.
6. Finally check if value of flag is 0 or 1 . If 0, means no vowel is found. Print one message to the user.
7. The isVowel function takes one character as input. It checks if the character is vowel or not. If yes, it returns 1 . Else, it returns 0.
8. We are using one switch case to find if a character is vowel or not. The switch case checks for all upper-case and lower-case vowel letters. If it is a vowel, it returns 1 else 0.

Sample Output :

Enter your string : This is a string
First vowel is : i

Enter your string : Hello World!!
First vowel is : e

Enter your string : abcd
First vowel is : a

Enter your string : bcd
No vowel found.

Leave a Reply