Write a program to input 20 names in an array and display all the names with the alphabet entered by the user. INPUT:Jaan, Kiara, Shona, Kriti Charecter: K Output: Kiara, Kriti
Answers
Answer:
import java.util.Scanner; public class KboatArrangeNames { public static void main(String args[]) { Scanner in = new Scanner(System.in); String names[] = new String[20]; System.out.println("Enter 20 names:"); for (int i = 0; i < names.length; i++) { names[i] = in.nextLine(); } //Bubble Sort for (int i = 0; i < names.length - 1; i++) { for (int j = 0; j < names.length - 1 - i; j++) { if (names[j].compareToIgnoreCase(names[j + 1]) > 0) { String temp = names[j + 1]; names[j + 1] = names[j]; names[j] = temp; } } } System.out.println("\nSorted Names"); for (int i = 0; i < names.length; i++) { System.out.println(names[i]); } } }
The following codes have been written using Python.
We first import the module to create the array later on. We assign a variable as a list to store the names to be entered. A loop is given to retrieve the names over a specified range of 20, as the question asks for 20 names. The names are appended to the list earlier assigned for the same. We then convert the list into an array. The letter to check for matching names is then entered. A new list is created to store the names starting with the given letter. Another loop is given to check if there are names starting with the given letter. If there are, the names get stored into the new list. If the count of the new list is greater than 1, it indicates that there are names starting with the given letter, and they are printed. If not, an appropriate statement is printed. Both conditions are tested for using a conditional statement.