Python Program to Print All Vowels
Extract and print all vowels from a given string, or -1 if no vowels are present.
Understand the Problem
Problem Statement
Accept a string S as the input and print all the vowels in S as the output. If there is no vowel in S then the program must print -1 as the output.
Constraints
- 1 <= Length of S <= 100
- S can contain uppercase and lowercase letters, digits, and special characters
- Vowels are defined as: a, e, i, o, u (both lowercase and uppercase)
- Output must preserve the order of vowels as they appear in the input string
Examples
letuscrackeuaThe vowels in 'letuscrack' are 'e' (position 1), 'u' (position 3), and 'a' (position 7). They are printed in their original order.
Sky-1The string 'Sky' contains no vowels (a, e, i, o, u), so the output is -1.
Solution
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main() {
char s[101];
fgets(s, sizeof(s), stdin);
// Remove newline if present
int len = strlen(s);
if (len > 0 && s[len-1] == '\n') {
s[len-1] = '\0';
len--;
}
char vowels[] = "aeiouAEIOU";
bool found = false;
for (int i = 0; i < len; i++) {
for (int j = 0; j < 10; j++) {
if (s[i] == vowels[j]) {
printf("%c", s[i]);
found = true;
break;
}
}
}
if (!found) {
printf("-1");
}
return 0;
}This C solution reads the input string using fgets(), which safely handles strings with spaces. It removes any trailing newline character. The algorithm uses two nested loops: the outer loop iterates through each character of the input string, and the inner loop checks if that character matches any vowel. When a match is found, the character is printed and we break from the inner loop. A boolean flag tracks whether any vowels were found, and if none were found, it prints -1.