Problem:
Write a program that generates one hundred lowercase letters randomly and
counts the occurrences of each letter:Output:
The lowercase letters are:
q u q i s a y n o j f o x i a o x m x n
x e n y l i b f h h r p j y c m q d b q
o i a z j a a w a b z e w s d g v u v b
y n a q s p f k d i f d d c z l z l j a
q w j v j m w f t e g z z x z l v f o i
The occurrences of each letter are:
8 a 4 b 2 c 5 d 3 e 6 f 2 g 2 h 6 i 6 j
1 k 4 l 3 m 4 n 5 o 2 p 6 q 1 r 3 s 1 t
2 u 4 v 4 w 5 x 4 y 7 z
q u q i s a y n o j f o x i a o x m x n
x e n y l i b f h h r p j y c m q d b q
o i a z j a a w a b z e w s d g v u v b
y n a q s p f k d i f d d c z l z l j a
q w j v j m w f t e g z z x z l v f o i
The occurrences of each letter are:
8 a 4 b 2 c 5 d 3 e 6 f 2 g 2 h 6 i 6 j
1 k 4 l 3 m 4 n 5 o 2 p 6 q 1 r 3 s 1 t
2 u 4 v 4 w 5 x 4 y 7 z
Solution:
import java.util.Random; public class Count { /** Main method */ public static void main(String args[]) { // Declare and create an array char[] chars = createArray(); // Display the array System.out.println("The lowercase letters are:"); displayArray(chars); // Count the occurrences of each letter int[] counts = countLetters(chars); // Display counts System.out.println(); System.out.println("The occurrences of each letter are:"); displayCounts(counts); } /** Create an array of characters */ public static char[] createArray() { // Declare an array of characters and create it char[] chars = new char[100]; Random generator = new Random(); // Create lowercase letters randomly and assign // them to the array String S ="abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < chars.length; i++) chars[i] = (char) S.charAt(generator.nextInt(26)); // Return the array return chars; } /** Display the array of characters */ public static void displayArray(char[] chars) { // Display the characters in the array 20 on each line for (int i = 0; i < chars.length; i++) { if ((i + 1) % 20 == 0) System.out.println(chars[i] + " "); else System.out.print(chars[i] + " "); } } /** Count the occurrences of each letter */ public static int[] countLetters(char[] chars) { // Declare and create an array of 26 int int[] counts = new int[26]; // For each lowercase letter in the array, count it for (int i = 0; i < chars.length; i++) counts[chars[i] - 'a']++; return counts; } /** Display counts */ public static void displayCounts(int[] counts) { for (int i = 0; i < counts.length; i++) { if ((i + 1) % 10 == 0) System.out.println(counts[i] + " " + (char)(i + 'a')); else System.out.print(counts[i] + " " + (char)(i + 'a') + " "); } } }
Program in c language
ReplyDeletehttps://ultratechbits.blogspot.com/2019/01/write-program-that-creates-char-type.html