Program opened below. You can scroll through the algorithm, Java code and output.

Sort Three Numbers Without an Array

Download .java

Question

Read three integers p, q and r and print them in descending order without using an array.

Step 1: Begin the program. Step 2: Create the input Scanner. Step 3: Read the first number p. Step 4: Read the second number q. Step 5: Read the third number r. Step 6: Declare a temporary variable for exchanging values. Step 7: Compare p with q. Step 8: If p is smaller, interchange p and q. Step 9: Compare the present p with r. Step 10: If p is smaller, interchange p and r. Step 11: The largest value is now stored in p. Step 12: Compare q with r. Step 13: If q is smaller, interchange q and r. Step 14: Print p, q and r in that order. Step 15: Stop.
Java
import java.util.*;
class ThreeDescending {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int p = sc.nextInt();
        int q = sc.nextInt();
        int r = sc.nextInt();
        int temp;
        if (p < q) {
            temp = p;
            p = q;
            q = temp;
        }
        if (p < r) {
            temp = p;
            p = r;
            r = temp;
        }
        if (q < r) {
            temp = q;
            q = r;
            r = temp;
        }
        System.out.println(p + " " + q + " " + r);
    }
}
Input: 2 9 7 Output: 9 7 2
← Previous Program 24 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.