Program opened below. You can scroll through the algorithm, Java code and output.
Program 70
Count Words Beginning and Ending with a Vowel
Question
Accept an upper-case sentence ending with ., ? or !. Count words whose first and last letters are vowels, then display the words in the required order (vowel-bounded words first, followed by the remaining words).
Algorithm
Step 1: Start.
Step 2: Declare the variables and data structures required for the task.
Step 3: Input and validate the sentence.
Step 4: Remove the terminator and split into words.
Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution.
Step 6: For each word, test whether its first and last letters belong to A, E, I, O or U.
Step 7: Count words satisfying both conditions.
Step 8: Collect qualifying and non-qualifying words separately, preserving original order.
Step 9: Store the computed result and prepare it for display.
Step 10: Display the count and the two groups joined by spaces.
Step 11: Stop.
Java program
Javaimport java.util.*;
class VowelBoundedWords {
static boolean vowel(char c) {
return "AEIOU".indexOf(c) >= 0;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine().trim();
if (!s.matches("[A-Z]+( [A-Z]+)*[.?!]")) {
System.out.println("INVALID INPUT");
return;
}
String[] words = s.substring(0, s.length() - 1).split(" ");
ArrayList<String> yes = new ArrayList<>(), no = new ArrayList<>();
for (String w : words) {
if (vowel(w.charAt(0)) && vowel(w.charAt(w.length() - 1))) {
yes.add(w);
}
else {
no.add(w);
}
}
System.out.println("NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = " + yes.size());
yes.addAll(no);
System.out.println(String.join(" ", yes));
}
}Sample output
Input: ANAMIKA AND SUSAN ARE NEVER GOING TO QUARREL ANYMORE.
Output:
NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 3
ANAMIKA ARE ANYMORE AND SUSAN NEVER GOING TO QUARREL