KnowledgeBoat Logo

Computer Applications

Write a program to input two characters from the keyboard. Find the difference (d) between their ASCII codes. Display the following messages:
If d = 0 : both the characters are same.
If d \< 0 : first character is smaller.
If d > 0 : second character is smaller.
Sample Input :
D
P
Sample Output :
d = (68 - 80) = -12
First character is smaller

Java

Java Library Classes

51 Likes

Answer

import java.util.Scanner;

public class KboatASCIIDiff
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter first character: ");
        char ch1 = in.next().charAt(0);
        System.out.print("Enter second character: ");
        char ch2 = in.next().charAt(0);
        
        int d = (int)ch1 - (int)ch2;
        if (d > 0)
            System.out.println("Second character is smaller");
        else if (d < 0)
            System.out.println("First character is smaller");
        else
            System.out.println("Both the characters are same");
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program to input two characters from the keyboard. Find the difference (d) between their ASCII codes. Display the following messages: If d = 0 : both the characters are same. If d \ 0 : first character is smaller. If d > 0 : second character is smaller. Sample Input : D P Sample Output : d = (68 - 80) = -12 First character is smallerBlueJ output of Write a program to input two characters from the keyboard. Find the difference (d) between their ASCII codes. Display the following messages: If d = 0 : both the characters are same. If d \ 0 : first character is smaller. If d > 0 : second character is smaller. Sample Input : D P Sample Output : d = (68 - 80) = -12 First character is smallerBlueJ output of Write a program to input two characters from the keyboard. Find the difference (d) between their ASCII codes. Display the following messages: If d = 0 : both the characters are same. If d \ 0 : first character is smaller. If d > 0 : second character is smaller. Sample Input : D P Sample Output : d = (68 - 80) = -12 First character is smaller

Answered By

16 Likes


Related Questions