Define a class to declare a character array of size ten, accept the characters into the array and display the characters with the highest and lowest ASCII (American Standard Code for Information Interchange) value. EXAMPLE: INPUT: 'R', 'z', 'q', 'A', 'N', 'p', 'm', 'U', 'Q', 'F' OUTPUT: Character with highest ASCII value = z Character with lowest ASCII value = A
Topic: Highest and lowest ASCII value in a character array
Answer
import java.util.Scanner;
class AsciiHighLow { public static void main(String args[]) { Scanner sc = new Scanner(System.in); char ch[] = new char[10];
System.out.println("Enter 10 characters :"); for(int i = 0; i < 10; i++) ch[i] = sc.next().charAt(0);
char hi = ch[0], lo = ch[0];
for(int i = 1; i < 10; i++) { if(ch[i] > hi) hi = ch[i]; if(ch[i] < lo) lo = ch[i]; }
System.out.println("Character with highest ASCII value = " + hi); System.out.println("Character with lowest ASCII value = " + lo); } }
A largest-and-smallest search, with one Java-specific point that makes it easy.
Characters can be compared directly with > and < because Java promotes each char to its Unicode (ASCII) value in an arithmetic context. So ch[i] > hi works exactly as it would for numbers — no call to (int) is needed, though writing one is harmless.
Initialise both trackers to the FIRST element, not to arbitrary values, and start the search loop at index 1. Setting hi = 0 would also work here, but setting lo = 0 would not, since no character has a code below 0 — initialising from the data itself avoids the whole problem.
Note that lowercase letters have HIGHER codes than uppercase: a = 97 while A = 65. That is why the sample answer is z for the highest and A for the lowest, even though A looks "bigger" on the page. Trace the sample and you will see z (122) beats every uppercase letter.
ch[] char[10] - the ten characters entered by the user hi char - character with the highest ASCII value so far lo char - character with the lowest ASCII value so far i int - loop variable sc Scanner - object used to read input