Write a Java program to input two numbers and perform all arithmetic operations. How to perform all arithmetic operation between two numbers in Java programming. Java program to find sum, difference, product, quotient and modulus of two given numbers.
Required knowledge
Arithmetic operators, Data types, Basic Input/Output
In previous post I explained to find the sum of two numbers.
Read more - Program to find sum of two numbers
Program to perform all arithmetic operations
/** * Java program to perform all arithmetic operations */ import java.util.Scanner; class Test { public static void main(String args[]) { int num1, num2; int sum, sub, mult, mod; float div; Scanner op=new Scanner(System.in); /* * Input two numbers from user */ System.out.print("Enter first number: "); num1=op.nextInt(); System.out.print("Enter second number:"); num2=op.nextInt(); /* * Perform all arithmetic operations */ sum = num1 + num2; sub = num1 - num2; mult = num1 * num2; div = (float)num1 / num2; mod = num1 % num2; /* * Print result of all arithmetic operations */ System.out.println("SUM = "+sum); System.out.println("DIFFERENCE = "+sub); System.out.println("PRODUCT = "+mult); System.out.println("QUOTIENT = "+div); System.out.println("MODULUS = "+mod); } }
Output:
Enter first number: 10 Enter second number:20 SUM = 30 DIFFERENCE = -10 PRODUCT = 200 QUOTIENT = 0.5 MODULUS = 10
In statement div = (float) num1 / num2;, I have typecasted num1 to float before the divide operation, to avoid integer division.