Write a program in Java to store 5 words in a Single Dimensional Array and frame a new word by
Taking out the first character of each word Arrange the letters of the new word in ascending order
and display the resultant word,
Sample Input: Computer, History, Physics, Biology, Mathematics
New Word: CHPBM
Sample Output: BCHMP
Answers
Program:
import java.util.*;
public class MyClass
{
public static void main(String args[])
{
Scanner Sc = new Scanner(System.in);
String A[] = new String[5];
char ch[] = new char[5];
System.out.println("Enter five words in an array : ");
for(int i = 0 ; i < 5 ; i++)
{
A[i] = Sc.next();
ch[i] = A[i].charAt(0);
}
for(int i = 0 ; i < 5 ; i++)
{
for(int j = 0 ; j < 5-i-1 ; j++)
{
if(Character.compare(ch[j],ch[j+1]) > 0)
{
char temp = ch[j];
ch[j] = ch[j+1];
ch[j+1] = temp;
}
}
}
for(int i = 0 ; i < 5 ; i++)
{
System.out.print(ch[i]);
}
}
}
Output:
Enter five words in an array :
Computer
History
Physics
Biology
Mathematics
BCHMP