w3resource

Java: Divide two numbers and print on the screen

Java Basic: Exercise-3 with Solution

Write a Java program to divide two numbers and print them on the screen.

Division is one of the four basic operations of arithmetic, the others being addition, subtraction, and multiplication. The division of two natural numbers is the process of calculating the number of times one number is contained within one another.

Pictorial Presentation:

Java dividing two numbers

Sample Solution:

Java Code:

public class Exercise3 {
    public static void main(String[] args) {
        // Calculate the result of the division 50/3
        int result = 50 / 3;

        // Print the result of the division
        System.out.println(result);
    }
} 

Explanation:

The above Java code defines a class called "Exercise3" with a "main()" method. When executed, it prints the result of the division operation 50 / 3 to the console, which is approximately 16.6667 (since it's integer division, it will be truncated to 16).

Sample Output:

16

Flowchart:

Flowchart: Java exercises: Divide two numbers and print on the screen

Sample solution using input from the user:

Java Code:

import java.util.Scanner;

public class Main {
  public static void main(String[] args) 
  {
    // Create a Scanner object to read input from the user
    Scanner input = new Scanner(System.in);
    
    // Prompt the user to input the first number
    System.out.print("Input the first number: ");
    
    // Read and store the first number
    int a = input.nextInt();
    
    // Prompt the user to input the second number
    System.out.print("Input the second number: ");
    
    // Read and store the second number
    int b = input.nextInt();
    
    // Calculate the division of a and b
    int d = (a / b);
    
    // Display a blank line for separation
    System.out.println();
    
    // Display the result of the division
    System.out.println("The division of a and b is: " + d);
  }
}

Explanation:

The above Java code takes two integer numbers as input from the user, performs division, and displays the result. It uses the "Scanner" class for input, divides 'a' by 'b', and prints the result as "The division of a and b is: [result]."

Sample Output:

Input the first number:  7
Input the second number:  2

The division of a and b is:3

Flowchart:

Flowchart: Java exercises: Divide two numbers and print on the screen

Java Code Editor:

Previous: Write a Java program to print the sum of two numbers.
Next: Write a Java program to print the result of the following operations.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.